Python Forum

Full Version: Partial convertion string to int in lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone!

I'm new in Python and I think it's amazing. I'm doing an automation project to convert a string in values in table.
Now, I'd like to insert in my work a string that works in my list. In particular I need that all items (string type) inside the list are converted in int to recognize it in forward operations.
List is similar to this list=['A', 'B', '3', 'C', '4']
I want that numbers are not strings, but ints.

Thanks a lot and Let's Python!! :D :D
What have you tried?
One way to describe it in spoken language: "for every member of list try to convert into int, except in case of value error when leave as it is"
Here, for loops are incredibly useful. i also used range to int only numbers -
aList = ['A', '4', 'G', '1', '3']
x = 0
for i in aList:
    if i in range(-9999, 9999): #IDK if there is a better way to identify a number
        aList[x] = int(i)
        x += 1
Untested btw
(Apr-22-2019, 07:49 PM)SheeppOSU Wrote: [ -> ]Untested btw
Do test,i think there are some problems,and there are better ways Wink

Do try something next time @satellite89,if it dos not work doesn't matter at all it's the effort that counts.
To make some code of @perfringo explanation.
def convert(value):
    try:
        return int(value)
    except ValueError:
        return value
Then can use this function in a couple of ways.
>>> lst = ['A', 'B', '3', 'C', '4']
>>> list(map(convert, lst))
['A', 'B', 3, 'C', 4]
>>> 
>>> [convert(i) for i in lst]
['A', 'B', 3, 'C', 4]
I solve this problem, but now I want to create sub lists on the main one.
mylist=['a','b','/',3,'/','c']
number 3 is an int, and I want to make a sub list inside mylist with this items: '/',3,'/'.
How could I do?
If this is solved mark it as solved and start a new question and please explain it better than you have Confused