python

python strip函数怎么使用

小亿
105
2023-09-26 01:12:39
栏目: 编程语言

strip函数可以用来移除字符串的头尾指定字符,默认移除字符串两端的空格或换行符。

基本用法:

string.strip([chars])

其中,string表示要操作的字符串,chars表示要移除的字符集合。如果不指定chars参数,默认移除字符串两端的空格或换行符。

示例:

string = "   hello world   "
new_string = string.strip()
print(new_string)  # 输出:hello world

如果要移除字符串中指定的字符,可以通过传入chars参数来实现。

示例:

string = "hello world"
new_string = string.strip("hld")
print(new_string)  # 输出:ello wor

在上面的示例中,strip函数移除了字符串"hello world"中的字符"h""l""d"

另外,还有lstrip函数和rstrip函数分别用于移除字符串左侧和右侧的指定字符。用法与strip函数类似。

更多用法可以参考Python官方文档:https://docs.python.org/3/library/stdtypes.html#str.strip

0
看了该问题的人还看了