Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Check if the last characters in a string are numbers

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!

like image 488
user2002290 Avatar asked Jan 23 '13 01:01

user2002290


People also ask

How do you check if last character of a string is a digit?

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.

How do you check if a character in a string is a number Python?

Python String isdigit() The isdigit() method returns True if all characters in a string are digits. If not, it returns False .

How do you check if a character in a string is a digit or letter Python?

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 .


1 Answers

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.

like image 110
Peter Graham Avatar answered Oct 11 '22 09:10

Peter Graham