Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find one number in a string in Python?

Tags:

python

string

I have a file called something like FILE-1.txt or FILE-340.txt. I want to be able to get the number from the file name. I've found that I can use

numbers = re.findall(r'\d+', '%s' %(filename))

to get a list containing the number, and use numbers[0] to get the number itself as a string... But if I know it is just one number, it seems roundabout and unnecessary making a list to get it. Is there another way to do this?


Edit: Thanks! I guess now I have another question. Rather than getting a string, how do I get the integer?

like image 908
user1058492 Avatar asked Nov 22 '11 22:11

user1058492


People also ask

How do you find a number in a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.

How do you find a number in a string?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.

How do you search for a part of a string in Python?

The find() string method is built into Python's standard library. It takes a substring as input and finds its index - that is, the position of the substring inside the string you call the method on.

How do you check if there is a digit in a string Python?

Python String isdigit() Method The isdigit() method returns True if all the characters are digits, otherwise False. Exponents, like ², are also considered to be a digit.


2 Answers

Use search instead of findall:

number = re.search(r'\d+', filename).group()

Alternatively:

number = filter(str.isdigit, filename)
like image 108
Andrew Clark Avatar answered Oct 08 '22 01:10

Andrew Clark


Adding to F.J's comment, if you want an int, you can use:

numbers = int(re.search(r'\d+', filename).group())
like image 36
ewegesin Avatar answered Oct 07 '22 23:10

ewegesin