python中strip和restrip
时间: 2023-11-04 14:59:10 浏览: 43
strip和rstrip是Python中的字符串方法,用于去除字符串中的指定字符。
strip方法用于去除字符串首尾的指定字符,默认情况下去除字符串首尾的空格。可以通过传入参数chars来指定要去除的字符集。例如,使用string.strip('n')将删除字符串首尾的n字符,使用string.strip()将删除字符串首尾的空格。示例结果如下:
- print(string.strip('n')):' www.python.com_i love python'
- print('网址:' + string.strip()):'网址:www.python.com_i love python'
- print(string.strip('on')):'www.python.com_i love pyth'
- print(string.strip('nnno')):' www.python.com_i love pyth'
rstrip方法类似于strip方法,但只去除字符串尾部的指定字符。同样可以传入参数chars来指定要去除的字符集。示例结果如下:
- print(string.rstrip('n')):' www.python.com_i love pytho'
- print(string.rstrip()):' www.python.com_i love pythonnn'
- print(string.rstrip('on')):' www.python.com_i love pyth'
- print(string.rstrip('nnno')):' www.python.com_i love pyth'