简体   繁体   English

删除特定索引处的字符 - python

[英]Remove char at specific index - python

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.我试过 calling.replace 但显然这会删除所有“0”,而且我找不到 function 会为我删除 position 4 处的字符。

Anyone have a hint for me?有人给我提示吗?

使用切片,重建字符串减去要删除的索引:

newstr = oldstr[:4] + oldstr[5:]

as a sidenote, replace doesn't have to move all zeros. 作为旁注, replace不必移动全零。 If you just want to remove the first specify count to 1: 如果您只想将第一个指定count删除为1:

'asd0asd0'.replace('0','',1)

Out: 日期:

'asdasd0'

This is my generic solution for any string s and any index i : 这是我对任何字符串s和任何索引i通用解决方案:

def remove_at(i, s):
    return s[:i] + s[i+1:]

另一种选择,使用列表理解和连接:

''.join([_str[i] for i in xrange(len(_str)) if i  != 4])

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'
rem = lambda x, unwanted : ''.join([ c for i, c in enumerate(x) if i != unwanted])
rem('1230004', 4)
'123004'

Try this code: 试试这段代码:

s = input() 
a = int(input()) 
b = s.replace(s[a],'')
print(b)
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 从零开始的索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM