python如何删除空白字符

2024-04-29

在Python中,可以使用strip()方法来删除字符串两端的空白字符(包括空格、制表符、换行符等)。

例如:

s = "  hello world  "
print(s.strip())  # 输出结果为"hello world"

如果想删除字符串中间的空白字符,可以使用replace()方法将空白字符替换为空字符串。

例如:

s = "hello  world"
s = s.replace(" ", "")
print(s)  # 输出结果为"helloworld"