29. Python strip()

发布时间:2023-12-08

Python strip()

更新:2022-07-24 13:06 strip() 函数根据给定的参数删除原始字符串副本中的尾随和前导字符。方法将此副本作为输出返回。

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

条带()参数:

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

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

条带()返回值

返回值始终是字符串。在找到第一个匹配之前,它从字符串的左侧和右侧进行搜索,如果到达字符串的末尾,它将停止移除。

投入 返回值
线 字符串的副本

Python 中 strip() 方法的示例

示例 strip() 在 Python 中是如何工作的?

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

输出:

python

示例 strip() 如何删除两边的空白?

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

输出:

Hii Python!