What actually happens when this code is executed:
text = "word1anotherword23nextone456lastone333"
numbers = [x for x in text if x.isdigit()]
print(numbers)
I understand, that []
makes a list, .isdigit()
checks for True or False if an element of string (text) is a number. However I am unsure about other steps, especially: what does that "x" do in front of for loop?
I know what the output is (below), but how is it done?
Output: ['1', '2', '3', '4', '5', '6', '3', '3', '3']
This is just standard Python list comprehension. It's a different way of writing a longer for
loop. You're looping over all the characters in your string and putting them in the list if the character is a digit.
See this for more info on list comprehension.
Using a for
loop, you would get the same result with:
numbers = []
for x in text:
if x.isdigit():
numbers.append(x)