Reputation: 7421
So I have written a lot of code and so far avoided importing or using regex and would prefer to keep it that way if possible.
Have a list which looks like this:
mylist = ["dog", "dogs", "dogs75", "75dogs", "cats75"]
I can get the indexes of various matched elements like this:
>>> [i for i, j in enumerate(mylist) if "cat" in j]
[4]
>>> [i for i, j in enumerate(mylist) if "dog" in j]
[0, 1, 2, 3]
>>>
The one I'm actually looking for is "dogs75"
, actually any string which contains an integer at the end.
Can this be done without importing re
?
Upvotes: 1
Views: 40
Reputation: 2011
[s for s in mylist if s[-1].isdigit()]
should give you the list you want
Upvotes: 0
Reputation: 1371
You can use isdecimal()
to check the last character:
>>> mylist = ["dog", "dogs", "dogs75", "75dogs", "cats75"]
>>> [i for i, j in enumerate(mylist) if j[-1].isdecimal()]
[2, 4]
You could also replace isdecimal
with isdigit
or isnumeric
if you are expected number-like characters that aren't the digits 0-9
Upvotes: 1
Reputation: 88236
You can use a list comprehension and check if the last character of each string is numeric:
[ix for ix, i in enumerate(mylist) if i[-1].isnumeric()]
# [2, 4]
Upvotes: 1