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?
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.
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.
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.
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.
Use search
instead of findall
:
number = re.search(r'\d+', filename).group()
Alternatively:
number = filter(str.isdigit, filename)
Adding to F.J's comment, if you want an int, you can use:
numbers = int(re.search(r'\d+', filename).group())
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