Câu hỏi phỏng vấn Python
Câu hỏi

How do I modify a string in python?

Câu trả lời

In Python, strings are immutable, which means that once a string is created, it cannot be altered. However, you can create a new string that is a variation of the original string. Here are some common ways to "modify" a string in Python:

  1. Concatenation: You can concatenate strings using the + operator to combine them into a new string.

    python Copy
    original = "Hello"
    modified = original + " World"  # "Hello World"
  2. Replacing Substrings: The replace() method creates a new string by replacing occurrences of a specified substring with a new substring.

    python Copy
    original = "Hello"
    modified = original.replace("e", "a")  # "Hallo"
  3. String Slicing: You can create a new string by slicing the original string, which means extracting a part of the string.

    python Copy
    original = "Hello World"
    modified = original[:5]  # "Hello"
  4. String Formatting: Python provides several methods to format strings, such as f-strings (formatted string literals) and the format() method.

    python Copy
    name = "Alice"
    age = 30
    modified = f"My name is {name} and I am {age} years old."  # "My name is Alice and I am 30 years old."
  5. Using join(): To combine a list of strings into a single string, you can use the join() method.

    python Copy
    words = ["Hello", "World"]
    modified = " ".join(words)  # "Hello World"
  6. Case Conversion: You can change the case of a string using methods like upper(), lower(), capitalize(), and title().

    python Copy
    original = "hello world"
    modified = original.capitalize()  # "Hello world"
  7. Stripping Whitespace: The strip(), lstrip(), and rstrip() methods can be ...

entry

entry

Gợi ý câu hỏi phỏng vấn

middle

What does the Python nonlocal statement do (in Python 3.0 and later)?

middle

Why would you use the pass statement?

expert

Is there any downside to the -O flag apart from missing on the built-in debugging information?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào