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 are the Wheels and Eggs? What is the difference?

middle

What is introspection/reflection and does Python support it?

middle

What is Monkey Patching and is it ever a good idea?

Bình luận

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

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