Tutorial Study Image

Python strip()

Python 中的 `strip()` 函数根据给定的参数移除原始字符串副本的前导和尾随字符。该方法将此副本作为输出返回。


string.strip([chars]) #where chars are those to remove from right & left
 

strip() 参数

`strip()` 函数将一组字符作为其参数。如果未提供 `chars`,则从字符串中移除前导和尾随的空格。

参数 描述 必需/可选
chars 要移除的前导和尾随字符 可选

strip() 返回值

返回值始终是一个字符串。它从字符串的左右两端开始搜索,直到找到第一个匹配项,如果到达字符串末尾则停止移除。

输入 返回值
字符串 字符串副本

Python 中 strip() 方法的示例

示例 1:strip() 在 Python 中如何工作?


string1 = ",,,,,rrttgg.....python....rrr"
# Removing characters
string2 = string1.strip(",.grt")

print(string2)
 

输出


python

示例 2:strip() 如何移除两侧的空格?


string1 = "  Hii Python!  "
# Removes white spaces
after_strip = string1.strip()
 

输出


Hii Python!