0

I'm working on python3 receiving a list of strings and I have to check if their elements are integers, floats or random string for future purposes.

list = ['3', 'random2', '5.05','1','Cool phrase']

What is the best way to do it? any recommended function?

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65

4 Answers4

1

I would use a try/except logic here, where I attempt to parse the string as an int, if it throws an exception, parse as a float, and if even that throws an exception, say that it is indeed a string like so.

def check_type(str):
    try:
        int(str)
        print(str, 'is a integer')
    except:
        try:
            float(str)
            print(str, 'is a float')
        except:
            print(str, 'is a string')

Then when I execute it on your list, I will get

lst = ['3', 'random2', '5.05', '1', 'Cool phrase']
for l in lst:
    check_type(l)
#3 is a integer
#random2 is a string
#5.05 is a float
#1 is a integer
#Cool phrase is a string
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

try below code:

l1 = ['3', 'random2', '5.05','1','Cool phrase']
for ele in l1:
    if "." in ele and ele.replace('.', '').isdigit():
        print("%s is float"%ele)
    elif ele.isdigit():
        print("%s is int"%ele)
    else:
        print("%s is string"%ele)

output:

3 is int 
random2 is string
5.05 is float 
1 is int
Cool phrase is string
Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19
-1

two simple ways to get type details.

`list1 = [3, 'random2', '5.05','1','Cool phrase']
 list2 = [type(element ) for element in list1]
 print (list2)`

list1 = [3, 'random2', '5.05','1','Cool phrase']
for element in list1:
    print (type(element ))
mkrana
  • 422
  • 4
  • 10
-2

What you need is regular expression.

And Python's re[https://docs.python.org/3.7/library/re.html] module can help you. for example:

>>> re.match(r"\d+.\d+", '24.12')
<_sre.SRE_Match object; span=(0, 5), match='24.12'>
>>> re.match(r"\d+", 24)
<_sre.SRE_Match object; span=(0, 2), match='24'>
>>> re.match(r"\d+", 24.12)
None
冯毅强
  • 1
  • 2