回答
这里有几种方法来做到这一点。
你可以用一个自己的切片替换整个字符串。
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
在任何情况下,你必须,因为他们是“不可改变的”,以取代与修改后的版本字符串的原始值(不变),一旦设置的值。
>>> s = "hello"
>>> print(s[:-3])
he
有关如何工作的说明,请参阅问题:good primer for python slice notation。
类型的 “hello”[2]
或 “你好”[: - 3]这是除去最后三个字母
希望回答这有助于
这不是被要求是什么;要求的是去掉最后三个,而不是前两个。 – 2010-12-13 07:18:35
我只是把注意力集中在“他”上,“好吧”:),虽然 – 2010-12-13 07:29:11
"hello"[:-3]
- 第一length - 3
字符。
"hello"[:2]
- 前2个字符。
"hello"[:2]
是这样做的最简单的方法,但是问题 的准确答案将会像Saif al Harthi所述的那样。 "hello"[:-3]
如果x是你的字符串,那么你可以使用x[:len(x)-3:+1]
来获得期望的结果
这可行,但它是一种非常糟糕的风格,效率低下,多余,因此容易出错。 – Davidmh 2014-08-15 11:39:15
- 1. Python的操作字符串
- 2. 的Python:字符串操作
- 3. Python在字符串中执行操作
- 4. Python字符串操作
- 5. Python字符串操作
- 6. 操作Python int /字符串
- 7. 字符串操作Python
- 8. 操作python中的字符串列表
- 9. python中的字符串操作
- 10. 字符串操作无法在python字符串上工作
- 11. Python字符串操作 - 在许多字符串中查找唯一的数字
- 12. Python的字符串操作(和值)
- 13. 使用xrange的Python字符串操作
- 14. 操作字符串内的操作符
- 15. 用python'\'字符串中的特殊字符操作
- 16. Python:操纵字符串中的字位
- 17. 在c中的字符串和字符串数组操作在
- 18. Python - 如何进行字符串操作?
- 19. Python快速字符串解析,操作
- 20. Python字符串操作问题
- 21. Python字符串语法错误+ =操作
- 22. Python问题输出。字符串操作
- 23. Python字符串格式化操作
- 24. Python字符串和列表操作
- 25. awk中字符串操作
- 26. 在C中的字符串操作
- 27. 在jQuery中的字符串操作
- 28. 在Perl中的字符串操作
- 29. 在ada中的字符串操作
- 30. 在AEM中的字符串操作?
请注意最后一个选项: 's =“helloxxxhelloxxx” s = s.replace(s [-3:],'' ) print s' – se1by 2015-10-07 09:06:15
@ se1by:好点...回答相应更新。 – martineau 2015-10-07 10:04:57