Python strip函数如何去除字符串中的空格?
发布时间:2023-10-25 22:25:36
Python中的strip函数可以去除字符串(str)的首尾空格。具体语法为:str.strip([chars])。
其中,str是要进行处理的字符串,chars是可选参数,用于指定需要去除的字符。如果不传递chars参数,则默认去除字符串首尾的空格。
strip函数会返回一个新的字符串,原始字符串不会被修改。
以下是strip函数的使用示例:
1. 去除字符串首尾空格:
s = " hello world " s = s.strip() print(s) # 输出:"hello world"
2. 去除指定字符:
s = " hello world "
s = s.strip(" d")
print(s) # 输出:"hello worl"
在第二个示例中,strip函数会将字符串首尾的空格和字符"d"都去除掉。
需要注意的是,strip函数只会去除字符串首尾的字符,不会处理字符串中间的字符。
如果需要去除字符串中间的空格,可以使用replace函数或正则表达式等方法。例如:
s = " hello world "
s = s.replace(" ", "") # 使用replace函数去除空格
print(s) # 输出:"helloworld"
或者使用正则表达式:
import re s = " hello world " s = re.sub(r"\s+", "", s) # 使用正则表达式去除空格 print(s) # 输出:"helloworld"
以上就是Python中strip函数去除字符串中空格的方法。
