Xonal
Xonal

Reputation: 1350

Python for-loop crashing because string length changes

Having a really silly problem. I'm iterating over a string and removing all non-alphabetical characters. The problem is that when I remove them, the length of the string decreases and my loop crashes because I go out of bounds.

for x in s:
    if x.isalpha() == False:
        s = s.replace(x, "")

Upvotes: 0

Views: 142

Answers (4)

mhawke
mhawke

Reputation: 87064

A list comprehension is the most Pythonic way to do this.

s = ''.join([x for x in s if x.isalpha()])

The list comprehension builds a list containing alpha characters only, and join() returns a string of those characters.

Upvotes: 0

zs2020
zs2020

Reputation: 54514

The trick is to loop from end to front if you insist to use loop...

This is the useful trick to handle the length change.

for x in s[::-1]:
    if x.isalpha() == False:
        s = s.replace(x, "")

Edit: I forgot to mention, to reverse a string, you can do s[::-1]

Upvotes: 1

jwodder
jwodder

Reputation: 57470

Use filter!

s = filter(str.isalpha, s)

Upvotes: 3

Parker
Parker

Reputation: 8851

Use a regex!

import re
regex = re.compile('[^a-zA-Z]') #Create a regex that allows on only A-Z and a-z
regex.sub('', s) #This will return the string, stripped of non alphabetical characters

Upvotes: 2

Related Questions