1. 程式人生 > 其它 >Python字串:strip、lstrip、rstrip去掉前導和末尾字元

Python字串:strip、lstrip、rstrip去掉前導和末尾字元

技術標籤:# 4.2 Pythonpython字串striplstriprstrip

str.strip([chars])

返回原字串的副本,移除其中的前導和末尾字元。 chars 引數為指定要移除字元的字串。 如果省略或為 None,則 chars 引數預設移除空格符。 實際上 chars 引數並非指定單個字首或字尾;而是會移除引數值的所有組合:
在這裡插入圖片描述
str.lstrip([chars])

返回原字串的副本,移除其中的前導字元。 chars 引數為指定要移除字元的字串。 如果省略或為 None,則 chars 引數預設移除空格符。 實際上 chars 引數並非指定單個字首;而是會移除引數值的所有組合:

在這裡插入圖片描述
str.rstrip([chars])

返回原字串的副本,移除其中的末尾字元。 chars 引數為指定要移除字元的字串。 如果省略或為 None,則 chars 引數預設移除空格符。 實際上 chars 引數並非指定單個字尾;而是會移除引數值的所有組合:
在這裡插入圖片描述

# coding:utf-8

info = '    my name is dewei    '
new_info = info.strip()
print('.' + new_info + '.')

info_01 = 'my name is dewei'
new_info_01 = info_01.strip(info_01)
print
(new_info_01) print(len(new_info_01)) new_str = 'abcde' print(new_str.lstrip('a')) print(new_str.rstrip('e'))

在這裡插入圖片描述