How do I modify a string in python?
How do I modify a string in python?
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:
Concatenation: You can concatenate strings using the + operator to combine them into a new string.
original = "Hello"
modified = original + " World" # "Hello World"
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"
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"
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."
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"
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"
Stripping Whitespace: The strip(), lstrip(), and rstrip() methods can be ...
entry
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào