亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python String strip() 函数与示例

什么是 Python strip()?

Python strip() 函数是 Python 库中可用的内置函数的一部分。 strip() 方法从原始字符串的开头和结尾删除给定的字符。默认情况下,strip() 函数从字符串的开头和结尾删除空格,并返回没有空格的相同字符串。

在本 Python 教程中,您将学习:

strip() 方法的语法

string.strip([characters])

参数

返回值

Python 字符串 strip() 将返回:

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

  1. Python 函数参数
  2. Python 闭包
  3. Java String charAt() 方法及示例
  4. Java String endsWith() 方法及示例
  5. 带有示例的 Python 字符串计数()
  6. Python String format() 举例说明
  7. Python 字符串长度 | len() 方法示例
  8. Python String find() 方法及示例
  9. 带有示例的 Python Lambda 函数
  10. 带有示例的 Python round() 函数
  11. 带有示例的 Python map() 函数
  12. Python 教程中的收益:生成器和收益与返回示例