Home > Mobile >  Conditional converting strings to integer
Conditional converting strings to integer

Time:07-17

Hi I want to clean up my code where I am converting a list of items to integers whenever possible in the python programming language.

example_list = ["4", "string1", "9", "string2", "10", "string3"]

So my goal (which is probably very simple) is to convert all items in the list from integers to integers and keep the actual strings as strings. The desired output of the program should be:

example_list = [4, "string1", 9, "string2", 10, "string3"]

I am looking for a nice clean method as I am sure that it is possible. I am curious about what nice methods there are.

CodePudding user response:

Based on your previous question, I am assuming you are using python. You can use try ... except clause:

example_list = ["4", "string1", "9", "string2", "10", "string3"]

def try_int(s):
    try:
        return int(s)
    except ValueError:
        return s

output = [try_int(s) for s in example_list] # or map(try_int, example_list)
print(*output) # [4, 'string1', 9, 'string2', 10, 'string3']

CodePudding user response:

Alternatively, you do either one:

examples = ["4", "string1", "9", "string2", "10", "string3"]

# for-loop to check
result = []

for item in examples:
    if item.isdigit():
        result.append(int(item))
    else:
        result.append(item)
        
print(result)

# List Comprehension 
ans = [int(x) if x.isdigit() else x for x in examples]

assert result == ans       # silence, because they are same
  • Related