Python按索引从字符串中删除字符的最佳方法 [英] Python best way to remove char from string by index

查看:173
本文介绍了Python按索引从字符串中删除字符的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从这样的字符串中删除一个字符:

I'm removing an char from string like this:

S = "abcd"
Index=1 #index of string to remove
ListS = list(S)
ListS.pop(Index)
S = "".join(ListS)
print S
#"acd"

我确信这不是最好的方法.

编辑我没有提到我需要操纵长度为 ~ 10^7 的字符串大小.所以关注效率很重要.

EDIT I didn't mentioned that I need to manipulate a string size with length ~ 10^7. So it's important to care about efficiency.

谁能帮帮我.哪种pythonic方式来做到这一点?

Can someone help me. Which pythonic way to do it?

推荐答案

你可以通过切片绕过所有列表操作:

You can bypass all the list operations with slicing:

S = S[:1] + S[2:]

或更普遍的

S = S[:Index] + S[Index + 1:]

可以在此处找到您问题的许多答案(包括此类答案):如何使用 python 从字符串中删除字符?.然而,这个问题名义上是关于按值删除,而不是按索引删除.

Many answers to your question (including ones like this) can be found here: How to delete a character from a string using python?. However, that question is nominally about deleting by value, not by index.

这篇关于Python按索引从字符串中删除字符的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆