温馨提示×

python strip()函数怎么使用

小亿
106
2023-08-19 03:52:59
栏目: 编程语言

Python中的strip()函数是用来删除字符串中的指定字符,默认情况下是删除字符串两端的空格或换行符。

可以使用以下语法来使用strip()函数:

string.strip([chars])

其中,string表示要操作的字符串,[chars]是可选参数,用来指定要删除的字符。如果不指定chars,则默认删除字符串两端的空格或换行符。

以下是一些使用strip()函数的示例:

示例1:删除字符串两端的空格

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

示例2:删除字符串两端的特定字符

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

示例3:删除字符串两端的换行符

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

需要注意的是,strip()函数不会修改原始字符串,而是返回一个新的字符串。

0