Python按索引从字符串中删除字符的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38066836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:16:49  来源:igfitidea点击:

Python best way to remove char from string by index

pythonstringpython-2.7python-3.xsubstring

提问by Alvaro Joao

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"

I'm sure that this is notthe best way to do it.

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

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

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

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

有人能帮我吗。哪种pythonic方法可以做到?

回答by Mad Physicist

You can bypass all the list operations with slicing:

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

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

or more generally

或更一般地

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

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.

您的问题的许多答案(包括此类)可以在这里找到:How to delete a character from a string using python? . 然而,这个问题名义上是关于按值删除,而不是按索引删除。

回答by Iron Fist

Slicing is the best and easiest approach I can think of, here are some other alternatives:

切片是我能想到的最好和最简单的方法,这里有一些其他的选择:

>>> s = 'abcd'
>>> def remove(s, indx):
        return ''.join(x for x in s if s.index(x) != indx)

>>> remove(s, 1)
'acd'
>>> 
>>> 
>>> def remove(s, indx):
        return ''.join(filter(lambda x: s.index(x) != 1, s))

>>> remove(s, 1)
'acd'

Remember that indexing is zero-based.

请记住,索引是从零开始的。

回答by min2bro

You can replace the Index character with "".

您可以用“”替换索引字符。

str = "ab1cd1ef"
Index = 3
print(str.replace(str[Index],"",1))

回答by Kate Kiatsiri

def missing_char(str, n):

  front = str[:n]   # up to but not including n
  back = str[n+1:]  # n+1 through end of string
  return front + back