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.

    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.

    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.

    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.

    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.

    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().

    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

How can you share global variables across modules?

senior

How is set() implemented internally?

senior

What's the difference between a Python module and a Python package?

Bình luận

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

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