Python 3 字符串方法?

发布于 2024-12-23 02:34:21 字数 143 浏览 3 评论 0原文

无论如何,是否可以在单个字符串中从一个索引删除或替换或类似的操作到另一个索引?

例如,如果我有一个像“first - Second - Third”这样的字符串,并且我想删除中间部分(“ - Second - ”),我该怎么做?

提前致谢。

Is there anyway to strip or replace or anything like that from one index to another index within a single string?

For example, if I have a string like "first - second - third" and I want to remove the middle part (" - second - "), how could I do this?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

喜爱纠缠 2024-12-30 02:34:21

您的字符串:

s = 'first - second - third'

以及可能的解决方案:

s.replace(' - second - ', '')

或者

''.join(s.split(' - ')[::2])

或者

''.join(s.split(' - second - '))

或者如果您知道索引:

s[:5] + s[-5:]

或者只是搜索第一个和最后一个空格:

s[:s.index(' ')] + s[s.rindex(' ')+1:]

它们都返回'firstthird'

Your string:

s = 'first - second - third'

and the possible solutions:

s.replace(' - second - ', '')

or

''.join(s.split(' - ')[::2])

or

''.join(s.split(' - second - '))

or if you know the indices:

s[:5] + s[-5:]

or just searching for the first and last space:

s[:s.index(' ')] + s[s.rindex(' ')+1:]

all of them return 'firstthird'

因为看清所以看轻 2024-12-30 02:34:21
"first - second - third".replace('- second -','')
"first - second - third".replace('- second -','')
蘑菇王子 2024-12-30 02:34:21

如果要删除的索引是 (i, j),那么您可以这样做:

myStr[:i] + myStr[j+1:]

If the indices to remove are (i, j), then you could do with:

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