Python str.rstrip 用法详解及示例
str.rstrip() 是 Python 字符串对象的一个方法,用于移除字符串右边(末尾)的指定字符或空格。其基本语法如下:
str.rstrip([chars])
参数 chars 是可选的,表示要移除的字符集合。如果未指定 chars 参数,则默认移除字符串末尾的空格(包括空格、制表符、换行符等)。
下面是三个示例来说明 str.rstrip() 的用法:
示例1
sentence = "Hello World "
new_sentence = sentence.rstrip()
print(new_sentence)
输出结果:
Hello World
在这个示例中,原始字符串 sentence 包含多个空格字符,rstrip() 方法会自动移除字符串末尾的所有空格字符,返回新字符串 new_sentence。
示例2
word = "Python is cool!"
new_word = word.rstrip("!")
print(new_word)
输出结果:
Python is cool
在这个示例中,原始字符串 word 包含一个感叹号字符(!),rstrip("!") 方法会移除字符串末尾的感叹号字符,返回新字符串 new_word。
示例3
text = "This is a test."
new_text = text.rstrip("test")
print(new_text)
输出结果:
This is a
在这个示例中,原始字符串 text 以单词 “test” 结尾,rstrip("test") 方法会移除字符串末尾的 “t”、”e”、”s”、”t” 这四个字符,返回新字符串 new_text。请注意,rstrip() 方法不会把字符串当做一个整词来处理,而是把它当做一个字符集合来处理。
极客教程