如何在Python中修剪字符?

发布于 2024-11-29 05:30:56 字数 117 浏览 2 评论 0原文

对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不语却知心 2024-12-06 05:30:56

您可以使用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.

空心↖ 2024-12-06 05:30:56

如果只是考虑字符数,切片听起来是您所追求的最合适的用例;但是,如果您知道要从字符串中修剪的实际字符串,您可以执行 rstrip

x = 'I am going'
>>> x.rstrip('ing')
'I am go'
>>> x.rstrip('noMatch')
'I am going'

更新

抱歉造成误导,但这些示例具有误导性,rstrip 的参数没有被处理为有序字符串,而是被处理为一个无序的字符集。

所有这些都是等效的

>>> x.rstrip('ing')
'I am go'
>>> x.rstrip('gni')
'I am go'
>>> x.rstrip('ngi')
'I am go'
>>> x.rstrip('nig')
'I am go'
>>> x.rstrip('gin')
'I am go'

更新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

x = 'I am going'
>>> x.rstrip('ing')
'I am go'
>>> x.rstrip('noMatch')
'I am going'

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

>>> x.rstrip('ing')
'I am go'
>>> x.rstrip('gni')
'I am go'
>>> x.rstrip('ngi')
'I am go'
>>> x.rstrip('nig')
'I am go'
>>> x.rstrip('gin')
'I am go'

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

于我来说 2024-12-06 05:30:56

使用字符串切片

>>> x = 'I am going'
>>> x[:-3]
'I am go'

Use string slicing.

>>> x = 'I am going'
>>> x[:-3]
'I am go'
挽梦忆笙歌 2024-12-06 05:30:56

您可以在字符串名称后面添加 [:-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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文