Basically I want to know how I would do this.
Here's an example string:
string = "hello123"
I would like to know how I would check if the string ends in a number, then print the number the string ends in.
I know for this certain string you could use regex to determine if it ends with a number then use string[:] to select "123". BUT if I am looping through a file with strings like this:
hello123 hello12324 hello12435436346
...Then I will be unable to select the number using string[:] due to differentiation in the number lengths. I hope I explained what I need clearly enough for you guys to help. Thanks!
We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.
Python String isdigit() The isdigit() method returns True if all characters in a string are digits. If not, it returns False .
isalnum() is a built-in Python function that checks whether all characters in a string are alphanumeric. In other words, isalnum() checks whether a string contains only letters or numbers or both. If all characters are alphanumeric, isalnum() returns the value True ; otherwise, the method returns the value False .
import re m = re.search(r'\d+$', string) # if the string ends in digits m will be a Match object, or None otherwise. if m is not None: print m.group()
\d
matches a numerical digit, \d+
means match one-or-more digits (greedy: match as many consecutive as possible). And $
means match the end of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With