[英]remove char in string at many specific index when index are in the list
[英]Remove char at specific index - python
我有一个字符串,其中有两个“0”(str),我只想删除索引 4 处的“0”(str)
我试过 calling.replace 但显然这会删除所有“0”,而且我找不到 function 会为我删除 position 4 处的字符。
有人给我提示吗?
使用切片,重建字符串减去要删除的索引:
newstr = oldstr[:4] + oldstr[5:]
作为旁注, replace
不必移动全零。 如果您只想将第一个指定count
删除为1:
'asd0asd0'.replace('0','',1)
日期:
'asdasd0'
这是我对任何字符串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])
切片工作(并且是首选方法),但只是需要更多操作的替代方案(但转换为列表不会受到任何影响):
>>> 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'
试试这段代码:
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
从零开始的索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.