strip() 函数是 Python 字符串的内置函数之一,它的作用是去除字符串开头和结尾的指定字符(默认为空格字符)。

strip() 函数的语法如下:

string.strip([chars])

其中,string 是要操作的字符串,chars 是可选参数,用于指定要去除的字符。

strip() 函数的具体作用如下:

  • 如果没有指定 chars 参数,则默认去除字符串开头和结尾的空格字符。
  • 如果指定了 chars 参数,则会去除字符串开头和结尾的包含在 chars 中的字符。
  • 返回去除指定字符后的新字符串。

示例:

string = '  Hello, World!  '
new_string = string.strip()  # 去除开头和结尾的空格字符
print(new_string)  # 输出:Hello, World!

string = '###Hello, World!###'
new_string = string.strip('#')  # 去除开头和结尾的#字符
print(new_string)  # 输出:Hello, World!
Python strip() 函数:去除字符串开头和结尾的字符

原文地址: https://www.cveoy.top/t/topic/fKTK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录