Python 字符串 strip() 函数:如何使用?[方法示例]

Python strip() 是什么?

Python strip() 函数是 Python 库中内置函数的一部分。strip() 方法会移除原始字符串开头和结尾指定的字符。默认情况下,strip() 函数会移除字符串开头和结尾的空白字符,并返回不包含空白字符的同一字符串。

strip() 方法的语法

string.strip([characters])

参数

  • characters: (可选) 指定的字符将被从原始字符串的开头或结尾移除。
  • 如果未提供 characters 参数,则会移除字符串开头和结尾的空白字符。

返回值

Python String strip() 将返回

  • 如果未指定要移除的字符,则返回从开头和结尾移除了空白字符的原始字符串。
  • 如果字符串的开头或结尾没有任何空白字符,则字符串将按原样返回,与原始字符串匹配。
  • 如果提供了 characters 参数,并且给定的字符匹配,则原始字符串开头或结尾的字符将被移除,其余部分将被返回。
  • 如果提供的字符不匹配原始字符串的开头或结尾,则字符串将按原样返回。

Python strip() 函数的示例

示例 1:Python 中的 strip() 方法

str1 = "Welcome to Guru99!"
after_strip = str1.strip()

输出

Welcome to Guru99!

示例 2:对无效数据类型的 strip()

Python String strip() 函数仅适用于字符串,如果用于列表、元组等其他数据类型,则会返回错误。

用于 list() 时的示例

mylist = ["a", "b", "c", "d"]
print(mylist.strip()) 

以上将引发错误

Traceback (most recent call last):
  File "teststrip.py", line 2, in <module>
    print(mylist.strip())
AttributeError: 'list' object has no attribute 'strip'

示例 3:不带字符参数的 strip()

str1 = "Welcome to Guru99!"
after_strip = str1.strip()
print(after_strip)

str2 = "Welcome to Guru99!"
after_strip1 = str2.strip()
print(after_strip1)

输出

Welcome to Guru99!
Welcome to Guru99!

示例 4:传递字符参数的 strip()

str1 = "****Welcome to Guru99!****"
after_strip = str1.strip("*")
print(after_strip)

str2 = "Welcome to Guru99!"
after_strip1 = str2.strip("99!")
print(after_strip1)
str3 = "Welcome to Guru99!"
after_strip3 = str3.strip("to")
print(after_strip3)

输出

Welcome to Guru99!
Welcome to Guru
Welcome to Guru99!

为什么使用 Python strip() 函数?

以下是使用 Python strip 函数的原因

  • 它有助于根据要从原始字符串中移除的字符来移除字符串开头和结尾的字符。
  • 如果提供的字符与原始字符串不匹配,则字符串将按原样返回。
  • 如果未指定要移除的字符,则将移除原始字符串开头和结尾的空白字符。
  • 如果开头或结尾没有空白字符,则字符串将按原样返回。

摘要

  • Python String strip() 方法是 Python 内置函数的一部分。该函数将移除原始字符串开头和结尾的指定字符。
  • 此函数在移除给定字符串开头和结尾的空白字符方面非常有用,如示例所示。
  • 它有助于根据要从原始字符串中移除的字符来移除字符串开头和结尾的字符。
  • 如果提供的字符与原始字符串不匹配,则字符串将按原样返回。
  • 如果未指定要移除的字符,则将移除原始字符串开头和结尾的空白字符。
  • 如果开头或结尾没有空白字符,则字符串将按原样返回。