可以使用字符串的replace()方法来删除空格。代码示例如下:
str = "Hello, world! This is a string with spaces."
# 删除字符串中的所有空格
str_without_spaces = str.replace(" ", "")
print(str_without_spaces)
输出结果为:
Hello,world!Thisisastringwithspaces.
另外,如果只想删除字符串开头或结尾的空格,可以使用strip()方法:
str = " Hello, world! "
# 删除字符串开头和结尾的空格
str_stripped = str.strip()
print(str_stripped)
输出结果为:
Hello, world!
注意:以上方法都会返回一个新的字符串,原始字符串不受影响。如果想要修改原始字符串,可以将结果赋值回原始变量。