Remove char at specific index – python
Question:
I have a string that has two “0” (str) in it and I want to remove only the “0” (str) at index 4
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.
Anyone have a hint for me?
Answers:
Use slicing, rebuilding the string minus the index you want to remove:
newstr = oldstr[:4] + oldstr[5:]
as a sidenote, replace
doesn’t have to move all zeros. If you just want to remove the first specify count
to 1:
'asd0asd0'.replace('0','',1)
Out:
'asdasd0'
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'
Another option, using list comprehension and join:
''.join([_str[i] for i in xrange(len(_str)) if i != 4])
Try this code:
s = input()
a = int(input())
b = s.replace(s[a],'')
print(b)
This is my generic solution for any string s
and any index i
:
def remove_at(i, s):
return s[:i] + s[i+1:]
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)
zero-based indexing
rem = lambda x, unwanted : ''.join([ c for i, c in enumerate(x) if i != unwanted])
rem('1230004', 4)
'123004'
I have a string that has two “0” (str) in it and I want to remove only the “0” (str) at index 4
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.
Anyone have a hint for me?
Use slicing, rebuilding the string minus the index you want to remove:
newstr = oldstr[:4] + oldstr[5:]
as a sidenote, replace
doesn’t have to move all zeros. If you just want to remove the first specify count
to 1:
'asd0asd0'.replace('0','',1)
Out:
'asdasd0'
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'
Another option, using list comprehension and join:
''.join([_str[i] for i in xrange(len(_str)) if i != 4])
Try this code:
s = input()
a = int(input())
b = s.replace(s[a],'')
print(b)
This is my generic solution for any string s
and any index i
:
def remove_at(i, s):
return s[:i] + s[i+1:]
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)
zero-based indexing
rem = lambda x, unwanted : ''.join([ c for i, c in enumerate(x) if i != unwanted])
rem('1230004', 4)
'123004'