Gre*_*ill 12
>>> s = "hello"
>>> print(s[:-3])
he
Run Code Online (Sandbox Code Playgroud)
有关这是如何工作的解释,请参阅问题:python切片表示法的良好入门.
这里有几种方法可以做到.
你可以用一片自己替换整个字符串.
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)
在任何情况下,您都必须用修改后的版本替换字符串的原始值,因为一旦设置为值,它们就是"不可变的"(不可更改).
| 归档时间: |
|
| 查看次数: |
17501 次 |
| 最近记录: |