Python 字符串 strip()

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

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战