如何在 Python 中使用 strip() 函数对字符串进行去除空格操作?
发布时间:2023-06-23 07:35:46
在 Python 中,strip() 函数是用于去除字符串首尾空格(包括换行符、制表符等)的常用方法。strip() 函数返回的是字符串副本,所以原始字符串不受影响。
strip() 函数使用方法如下:
str.strip([chars])
其中,str 表示待去空格的字符串,chars 表示可选的指定字符集合,如果指定了 chars,则将首尾字符集合中的字符去除;如果未指定 chars,则将首尾空白符去除。
示例代码如下:
str1 = " hello "
str2 = "Hello\t
"
# 去除首尾空白符
print(str1.strip()) # 输出 "hello"
print(str2.strip()) # 输出 "Hello"
# 去除指定字符集合
print("------12345------".strip('-')) # 输出 "12345"
print("***hello#world***".strip('*#')) # 输出 "hello#world"
需要注意的是,strip() 函数只能去除首尾空格,如果需要去除字符串内部的空格,则可以使用 replace() 函数来进行替换操作。
示例代码如下:
str3 = "h e l l o"
no_space_str = str3.replace(' ', '')
print(no_space_str) # 输出 "hello"
最后需要注意的是,strip() 函数返回的是一个新字符串,原字符串不会被修改,如果需要修改原字符串,可以使用赋值操作来完成。
示例代码如下:
str4 = " hello " str4 = str4.strip() # 去除首尾空白符 print(str4) # 输出 "hello"
