在Python中,strip()
函数用于移除字符串开头和结尾的指定字符。
基本用法
移除特定字符
str3 = '1 11 111 111 1111 Learn Python Programming Tutorial 1111 111 11 1'
str4 = str3.strip('1')
print("Stripped '1' characters:", str4)
text = " hello world! \n"
stripped_text = text.strip()
print("Stripped Text:", stripped_text)
text_with_special_chars = "---hello world!!!---"
stripped_special_chars = text_with_special_chars.strip("-!")
print("Stripped Special Characters:", stripped_special_chars)
只移除左边的空白字符
只移除右边的空白字符
text = " Hello World! "
print(text.rstrip())
text = " Hello World! "
print(text.rstrip())
移除字符串中的多个指定字符
result = string.strip("!")
print("Stripped '!' characters:", result)
如果需要移除字符串中的所有指定字符,可以使用str.replace()
方法:
注意事项
-
strip()
函数不会修改原始字符串,而是返回一个新的字符串。
-
可以通过传入参数指定要去除的字符集合。
-
如果不指定参数,
strip()
默认移除字符串两端的空白字符。
希望这些示例能帮助你理解如何在Python中使用strip()
函数。
本文《python中strip函数怎么用》系
辅导客考试网原创,未经许可,禁止转载!合作方转载必需注明出处:https://www.fudaoke.com/exam/154431.html