Python中的字符串操作

rec*_*gle 4 python string

我在python中有一个字符串,我想取下最后三个字符.我该怎么做?

所以把'你好'变成'他'.

Gre*_*ill 12

>>> s = "hello"
>>> print(s[:-3])
he
Run Code Online (Sandbox Code Playgroud)

有关这是如何工作的解释,请参阅问题:python切片表示法的良好入门.


mar*_*eau 8

这里有几种方法可以做到.

你可以用一片自己替换整个字符串.

s = "hello"
s = s[:-3] # string without last three characters
print s
# he
Run Code Online (Sandbox Code Playgroud)

或者,您可以显式地从字符串中删除最后三个字符,然后将其分配回字符串.虽然可读性更强,但效率较低.

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
Run Code Online (Sandbox Code Playgroud)

在任何情况下,您都必须用修改后的版本替换字符串的原始值,因为一旦设置为值,它们就是"不可变的"(不可更改).