Python中的strip()函数如何去除字符串中的空格
发布时间:2023-09-25 20:16:42
strip()函数用于去除字符串前后的空格,默认情况下会去除字符串前后的所有空格。具体用法如下:
string.strip([chars])
其中,string是要操作的字符串,chars是一个可选参数,用于指定要删除的字符。
如果不给定chars参数,strip()函数会默认删除字符串前后的所有空格,例如:
string = " hello world " print(string.strip())
输出结果为:
hello world
如果给定了chars参数,strip()函数会删除字符串前后包含在chars中的字符,例如:
string = "----hello world----"
print(string.strip("-"))
输出结果为:
hello world
注意,strip()函数只会删除字符串前后的字符,中间的字符不会被处理。如果想要删除字符串中的所有空格,可以使用replace()函数:
string = " hello world "
print(string.replace(" ", ""))
输出结果为:
helloworld
strip()函数的返回值是一个新的字符串,原始字符串不会被修改。如果想修改原始字符串,可以将strip()函数的返回值重新赋值给原始字符串。
总结一下,通过strip()函数可以方便地删除字符串前后的空格或指定的字符。如果需要删除字符串中的所有空格,可以使用replace()函数进行替换操作。
