Home > Article > Backend Development > How to delete strings in python
In python, Strings are immutable, which means that individual characters of the string cannot be modified directly. But there are ways to delete parts of the string.
The following are some commonly used methods to delete string content:
string = "Hello, World!" new_string = string[:7] + string[8:] print(new_string)# 输出: Hello World!
replace()
method to replace the content in the string with an empty string. This method replaces the specified string or substring with another string. If you replace it with an empty string, it is equivalent to deleting that part of the content. For example:string = "Hello, World!" new_string = string.replace(", ", "") print(new_string)# 输出: HelloWorld!
join()
method and list comprehension to split the string into a list of characters and rejoin it into a new string with the empty string. For example:string = "Hello, World!" new_string = ''.join([char for char in string if char != ',']) print(new_string)# 输出: Hello World!
Please note that in Python, strings are immutable, so deleting the string content actually creates a new string, while the original string remains unchanged.
The above is the detailed content of How to delete strings in python. For more information, please follow other related articles on the PHP Chinese website!