Python strip函数几种用法
在Python中,strip()函数是用来去除字符串两端的指定字符(默认为空格)的函数。strip()函数常用于清除用户输入的字符串中的空白字符,也可以用来去除指定的字符。在本文中,我们将详细介绍strip()函数的几种用法。
基本用法
strip()函数的基本语法如下:
string.strip([chars])
其中,string为要操作的字符串,chars为可选参数,用来指定要去除的字符。
示例代码:
string = " hello world "
result = string.strip()
print(result)
运行结果:
hello world
在上面的示例中,去除了字符串两端的空格字符。
去除指定字符
如果想去除字符串中指定的字符,可以在strip()函数中传入要去除的字符作为参数。
示例代码:
string = "***hello world***"
result = string.strip("*")
print(result)
运行结果:
hello world
在上面的示例中,去除了字符串两端的*字符。
去除左端字符
除了strip()函数去除字符串两端的字符外,还有lstrip()函数可以仅去除左端字符,其基本语法如下:
string.lstrip([chars])
示例代码:
string = " hello world"
result = string.lstrip()
print(result)
运行结果:
hello world
在上面的示例中,去除了字符串左端的空格字符。
去除右端字符
与lstrip()函数相对应,还有rstrip()函数可以仅去除右端字符,其基本语法如下:
string.rstrip([chars])
示例代码:
string = "hello world "
result = string.rstrip()
print(result)
运行结果:
hello world
在上面的示例中,去除了字符串右端的空格字符。
多个字符一起去除
strip()函数不仅可以去除单个字符,还可以同时去除多个字符。
示例代码:
string = "###hello world###"
result = string.strip("#")
print(result)
运行结果:
hello world
在上面的示例中,同时去除了字符串两端的#字符。
结论
在本文中,我们详细介绍了strip()函数的几种用法,包括基本用法、去除指定字符、去除左端字符、去除右端字符、多个字符一起去除等。通过灵活运用strip()函数,可以方便地清除字符串两端的空白字符或指定字符,提高代码的可读性和实用性。