如何在Python中修剪字符?
对 Python 很陌生,有一个非常简单的问题。我想从字符串中删除最后 3 个字符。这样做的有效方法是什么?
示例 I am go
变为 I am go
Very new to Python and have very simple question. I would like to trim the last 3 characters from string. What is the efficient way of doing this?
Example I am going
becomes I am go
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
new_str = old_str[:-3]
,这表示从开头到结尾之前的三个字符。You can use
new_str = old_str[:-3]
, that means all from the beginning to three characters before the end.如果只是考虑字符数,切片听起来是您所追求的最合适的用例;但是,如果您知道要从字符串中修剪的实际字符串,您可以执行 rstrip
更新
抱歉造成误导,但这些示例具有误导性,
rstrip
的参数没有被处理为有序字符串,而是被处理为一个无序的字符集。所有这些都是等效的
更新2
如果正在寻求后缀和前缀剥离,现在有专门的内置支持这些操作。
https://www.python .org/dev/peps/pep-0616/#remove-multiple-copies-of-a-prefix
Slicing sounds like the most appropriate use case you're after if it's mere character count; however if you know the actual string you want to trim from the string you can do an rstrip
UPDATE
Sorry to have mislead but these examples are misleading, the argument to
rstrip
is not being processed as an ordered string but as an unordered set of characters.all of these are equivalent
Update 2
If suffix and prefix stripping is being sought after there's now dedicated built in support for those operations.
https://www.python.org/dev/peps/pep-0616/#remove-multiple-copies-of-a-prefix
使用字符串切片。
Use string slicing.
您可以在字符串名称后面添加 [:-3]。这将为您提供一个字符串,其中包含从头开始到倒数第三个字符的所有字符。或者,如果您想删除前 3 个字符,可以使用 [3:]。同样,[3:-3] 会给你一个字符串,其中前 3 个字符被删除,最后 3 个字符被删除。
You could add a [:-3] right after the name of the string. That would give you a string with all the characters from the start, up to the 3rd from last character. Alternatively, if you want the first 3 characters dropped, you could use [3:]. Likewise, [3:-3] would give you a string with the first 3, and the last 3 characters removed.