Python中的字符串操作
我在Python里有一个字符串,我想把最后三个字符去掉。我该怎么做呢?
比如把'hello'变成'he'。
6 个回答
4
"hello"[:-3]
- 这个意思是取字符串"hello"的前面部分,去掉最后3个字符。
"hello"[:2]
- 这个意思是取字符串"hello"的前面2个字符。
12
>>> s = "hello"
>>> print(s[:-3])
he
想了解这个是怎么回事,可以看看这个问题:关于Python切片语法的好入门。
8
这里有几种方法可以做到这一点。
你可以用字符串的一部分来替换整个字符串。
s = "hello"
s = s[:-3] # string without last three characters
print s
# he
另外,你也可以明确地去掉字符串最后三个字符,然后把这个新字符串再赋值回去。虽然这种方法可能更容易理解,但效率上会差一些。
s = "hello"
s = s.rstrip(s[-3:]) # s[-3:] are the last three characters of string
# rstrip returns a copy of the string with them removed
print s
# he
无论如何,你都需要把字符串的原始值替换成修改后的版本,因为一旦设置了值,字符串就是“不可变”的(也就是不能更改的)。