删除特定索引处的字符 - python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14198497/
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
Remove char at specific index - python
提问by tgunn
I have a string that has two "0" (str) in it and I want to remove only the "0" (str) at index 4
我有一个字符串,其中有两个“0”(str),我只想删除索引 4 处的“0”(str)
I have tried calling .replace but obviously that removes all "0", and I cannot find a function that will remove the char at position 4 for me.
我试过调用 .replace 但显然删除了所有“0”,我找不到一个函数可以为我删除位置 4 的字符。
Anyone have a hint for me?
有人对我有提示吗?
采纳答案by Martijn Pieters
Use slicing, rebuilding the string minus the index you want to remove:
使用切片,重建字符串减去要删除的索引:
newstr = oldstr[:4] + oldstr[5:]
回答by root
as a sidenote, replacedoesn't have to move all zeros. If you just want to remove the first specify countto 1:
作为旁注,replace不必移动所有零。如果您只想删除第一个指定count为 1:
'asd0asd0'.replace('0','',1)
Out:
出去:
'asdasd0'
'asdasd0'
回答by Jon Clements
Slicing works (and is the preferred approach), but just an alternative if more operations are needed (but then converting to a list wouldn't hurt anyway):
切片有效(并且是首选方法),但如果需要更多操作,这只是一种替代方法(但无论如何转换为列表都不会受到伤害):
>>> a = '123456789'
>>> b = bytearray(a)
>>> del b[3]
>>> b
bytearray(b'12356789')
>>> str(b)
'12356789'
回答by mclafee
Another option, using list comprehension and join:
另一种选择,使用列表理解和连接:
''.join([_str[i] for i in xrange(len(_str)) if i != 4])
回答by HARRY47
Try this code:
试试这个代码:
s = input()
a = int(input())
b = s.replace(s[a],'')
print(b)
回答by ?ngelo Polotto
This is my generic solution for any string sand any index i:
这是我对任何字符串s和任何索引的通用解决方案 i:
def remove_at(i, s):
return s[:i] + s[i+1:]
回答by Shishir
def remove_char(input_string, index):
first_part = input_string[:index]
second_part - input_string[index+1:]
return first_part + second_part
s = 'aababc'
index = 1
remove_char(s,index)
ababc
zero-based indexing
基于零的索引
回答by bhupen.chn
rem = lambda x, unwanted : ''.join([ c for i, c in enumerate(x) if i != unwanted])
rem('1230004', 4)
'123004'

