簡體   English   中英

刪除特定索引處的字符 - python

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM