Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
You don't have to cast your input "n" to a list. Your input will be a string and in essence a string is just a list of characters.
So you could do the following:
n = input()
for char in n:
if char == "a":
# do your thing -
p100sch14495y@TipsyTapir that's a rather inconvenient way to do it. I would use string replace with a count of 1, if his question was worded correctly.
@highlight
print(input().replace("a", "", 1)) -
@TipsyTapir While Python Strings are iterable and indexable, they are also immutable
@sharief
You modify the list you are iterating over. I will show you what happens (this is pseudocode, obviously):
n = "bar"
k=['b', 'a', 'r']
len(n) == 3
Steps of for j in range(3):
j = 0; k[0] = 'b'
j = 1; k[1] = 'a'; k.pop('a'); k = ['b', 'r']
j = 2; k[2] โฌ IndexError happens here, as k only has two elements, and not three.
What could you do instead?
Python Strings have a .replace method (e.g. n = n.replace("a", "").
Alternatively (if you don't actually have a string, but a list if something else) you could also do this:
while "a" in k:
k.pop(k.index("a")) -
@p100sch Yep should have read the complete question. I was more focusing on the index out of range error. Should have noticed he just wanted to replace some value. My bad ๐
n=input( )
k=list(n)
for j in range(len(k)):
if k[j]=="a":
k.pop(j)
print(k)
''' i want to print the list by removing a letter "a" but it is showing index error why ? help me out'''
question