我有一个字符串中包含两个 "0" (str),我希望仅删除索引为4的 "0" (str)。
我尝试使用 .replace 方法,但显然这将删除所有的 "0",而我找不到一个函数可以帮助我仅删除位置为4的字符。
有人能给我一点提示吗?
我有一个字符串中包含两个 "0" (str),我希望仅删除索引为4的 "0" (str)。
我尝试使用 .replace 方法,但显然这将删除所有的 "0",而我找不到一个函数可以帮助我仅删除位置为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函数:
''.join([_str[i] for i in xrange(len(_str)) if i != 4])
''.join([x for x in _str if x not in forbidden_chars])
得到了解决。 - Brandon Kuczenski>>> 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'
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)
尝试这段代码:
s = input()
a = int(input())
b = s.replace(s[a],'')
print(b)