str.strip([chars])
使用 strip 方法从字符串的两侧删除尾随空格或字符。例如:
string = " Apple Apple Apple no apple in the box apple apple "
stripped_string = string.strip()
print(stripped_string)
left_stripped_string = (
stripped_string
.lstrip('Apple')
.lstrip()
.lstrip('Apple')
.lstrip()
.lstrip('Apple')
.lstrip()
)
print(left_stripped_string)
capitalized_string = left_stripped_string.capitalize()
print(capitalized_string)
right_stripped_string = (
capitalized_string
.rstrip('apple')
.rstrip()
.rstrip('apple')
.rstrip()
)
print(right_stripped_string)
Output:
Apple Apple Apple no apple in the box apple apple
no apple in the box apple apple
No apple in the box apple apple
No apple in the box
在上面的代码片段中,使用了 lstrip 和 rstrip 方法,它们分别从字符串的左侧和右侧删除尾随空格或字符。还使用了 capitalize 方法,它将字符串转换为句子大小写