在Python中删除字符串中的空格,你可以使用以下几种方法:
1. 使用 `strip()` 方法去除字符串开头和结尾的空格。
my_string = " Example with spaces "
stripped_string = my_string.strip()
print(stripped_string) 输出: "Example with spaces"
2. 使用 `lstrip()` 方法仅去除字符串开头的空格。
my_string = " * it is blank space test * "
stripped_string = my_string.lstrip()
print(stripped_string) 输出: "* it is blank space test *"
3. 使用 `rstrip()` 方法仅去除字符串结尾的空格。
my_string = " * it is blank space test * "
stripped_string = my_string.rstrip()
print(stripped_string) 输出: "* it is blank space test *"
4. 使用 `replace()` 方法将所有空格替换为空字符串。
my_string = " Example with spaces "
stripped_string = my_string.replace(" ", "")
print(stripped_string) 输出: "Examplewithspaces"
5. 使用正则表达式 `re.sub()` 方法匹配并替换所有空格。
import re
my_string = " Example with spaces "
stripped_string = re.sub(" ", "", my_string)
print(stripped_string) 输出: "Examplewithspaces"