Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
<class 'str'> ?
#1
Why is that '\d' in a regular expression finds digits but then if those digits are stored in a variable, print(type(variable)) returns <class 'str'>?

import re

string = '''
10.00 22.34 31.23
'''

test_re = re.compile(r'\d')
test = test_re.findall(string)
print(test)

for i in test:
 print(type(i))
Output:
['1', '0', '0', '0', '2', '2', '3', '4', '3', '1', '2', '3'] <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'>
Reply
#2
regular expressions are all about strings. It's a char that is a digit, it is not expected to cast the result to numeric type. It's also evident from the list that you print - it's a list of str, not int
pprod likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Because digits are strings. Did you think it was converting the string to an int?
pprod likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020