strip()
方法用于移除给定字符串开头和结尾的所有空白字符。
示例
message = ' Learn Python '
# remove leading and trailing whitespaces
print(message.strip())
# Output: Learn Python
字符串 strip() 语法
string.strip([chars])
strip() 参数
该方法接受一个可选参数 - chars
- chars - 指定要从字符串左右两部分移除的字符集
注意:如果未提供 chars 参数,则会移除字符串开头和结尾的所有空白字符。
strip() 返回值
该方法返回一个移除了开头和结尾空白字符/字符的字符串。
示例 1:从字符串中移除空白字符
string = ' xoxo love xoxo '
# leading and trailing whitespaces are removed
print(string.strip())
输出
xoxo love xoxo
示例 2:从字符串中移除字符
string = ' xoxo love xoxo '
# all <whitespace>,x,o,e characters in the left
# and right of string are removed
print(string.strip(' xoe'))
输出
lov
注意事项:
- 从左侧移除字符,直到与
chars
参数中的字符不匹配。 - 从右侧移除字符,直到与
chars
参数中的字符不匹配。
示例 3:使用 strip() 移除换行符
我们也可以使用 strip()
方法从字符串中移除换行符。例如,
string = '\nLearn Python\n'
print('Original String: ', string)
new_string = string.strip()
print('Updated String:', new_string)
输出
Original String: Learn Python Updated String: Learn Python
另请阅读