Safely cast strings to ints in a list of tuples

convert list of strings to ints python
convert tuple to int
convert list to string python
convert string to int python
python convert list elements to int
int to tuple python
convert string to float python
how to convert all strings in a list to int

I have a list of tuples like so:

[('1001794', 'Us/Eastern', '2', '1', '3', '4', '5')
('1001832', 'Us/Central', '2', '3', '4', '4', '5')
('1001848', 'Us/Central', '2', '4', '5', '4', '5')
('1001855', 'Us/Central', '2', '1', '4', '4', '5')
('1001899', 'Us/Central', '2', '1', '4', '3', '5')
('1001914', 'Us/Pacific', '1', '4', '2', '4', '5')
('1001971', 'Us/Pacific', '3', '4', '2', '3', '5')
('1002021', 'Us/Eastern', '2', '1', '4', '4', '5')
('1002026', 'Us/Central', '2', '1', '4', '4', '2')
('1002028', 'Us/Eastern', '2', '1', '4', '4', '5')
('1002041', 'Us/Eastern', '2', '4', '3', '5', '4')]

And I need to convert all the numbers in there to numbers. I don't mind if I have to do 6 different list comprehensions if necessary, but I still can't wrap my head around list comprehension enough to make one from scratch properly. I tried doing:

[x = (int(x[0]),x[1],int(x[2]),int(x[3]),int(x[4]),int(x[5]),int(x[6])) for x in tlist]

But it tells me it's invalid syntax, and I'm not sure why?

Use str.isdigit:

[tuple(int(y) if y.isdigit() else y for y in x) for x in tup]
# [(1001794, 'Us/Eastern', 2, 1, 3, 4, 5), ...]

This is assuming the numbers in your strings are integers. tup is your data structure.


To handle negative integers, use a function encapsulating a try-except block (read about the EAFP principle):

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

[tuple(try_convert(y) for y in x) for x in tup]
# [(1001794, 'Us/Eastern', 2, 1, 3, 4, 5), ...]    

To handle ints and floats, you may use a nested block:

def try_convert(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s 

Python List list() Method, elements are put between parentheses instead of square bracket. Method #1 : Naive Method This is most generic method that strikes any programmer while performing this kind of operation. Just looping over whole list and convert each of the string of list to int by type casting.

This worked for me:

y = [('1001794', 'Us/Eastern', '2', '1', '3', '4', '5'),
     ('1002041', 'Us/Eastern', '2', '4', '3', '5', '4')]
x = [(int(x[0]),x[1],int(x[2]),int(x[3]),int(x[4]),int(x[5]),int(x[6])) for x in y]
print(x)
[(1001794, 'Us/Eastern', 2, 1, 3, 4, 5), (1002041, 'Us/Eastern', 2, 4, 3, 5, 4)]

You just need the x = outside the [.

Python, How do I convert a list of strings to a list of integers in python? Method #1 : Using eval () + list comprehension This problem can be easily performed as one liner using the inbuilt function of eval (), which performs this task of string to tuple conversion and list comprehension.

If you know where the ints are, you can use Extended Iterable Unpacking to simplify the list comprehension you where trying to use:

[(int(x), y, *map(int,v)) for x, y, *v in l]

[(1001794, 'Us/Eastern', 2, 1, 3, 4, 5),
 (1001832, 'Us/Central', 2, 3, 4, 4, 5),
 (1001848, 'Us/Central', 2, 4, 5, 4, 5),
 (1001855, 'Us/Central', 2, 1, 4, 4, 5),
 (1001899, 'Us/Central', 2, 1, 4, 3, 5),
 (1001914, 'Us/Pacific', 1, 4, 2, 4, 5),
 (1001971, 'Us/Pacific', 3, 4, 2, 3, 5),
 (1002021, 'Us/Eastern', 2, 1, 4, 4, 5),
 (1002026, 'Us/Central', 2, 1, 4, 4, 2),
 (1002028, 'Us/Eastern', 2, 1, 4, 4, 5),
 (1002041, 'Us/Eastern', 2, 4, 3, 5, 4)]

Python, How do you join a list of integers in python? Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair . If std:: is_trivially_destructible < Ti > :: value is true for every Ti in Types , the destructor of tuple is trivial.

is this the Answer your looking of ?

list = []
newList = []

list = [
        ('1001794', 'Us/Eastern', '2', '1', '3', '4', '5'),
        ('1001832', 'Us/Central', '2', '3', '4', '4', '5'),
        ('1001848', 'Us/Central', '2', '4', '5', '4', '5'),
        ('1001855', 'Us/Central', '2', '1', '4', '4', '5'),
        ('1001899', 'Us/Central', '2', '1', '4', '3', '5'),
        ('1001914', 'Us/Pacific', '1', '4', '2', '4', '5'),
        ('1001971', 'Us/Pacific', '3', '4', '2', '3', '5'),
        ('1002021', 'Us/Eastern', '2', '1', '4', '4', '5'),
        ('1002026', 'Us/Central', '2', '1', '4', '4', '2'),
        ('1002028', 'Us/Eastern', '2', '1', '4', '4', '5'),
        ('1002041', 'Us/Eastern', '2', '4', '3', '5', '4')
        ]

newList = [[int(x[0]), x[1], int(x[2]), int(x[3]), int(x[4]), int(x[5]), int(x[6])] for x in list]

print(newList)

Python, Python | Program to print duplicates from a list of integers · Python - Join Tuples to Integers in Tuple List · Python | Convert numeric String to integers in mixed List​  Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)

Python 2.7 Tutorial, Python | Convert list of strings to list of tuples. Sometimes we deal with different types of data types and we require to inter convert from one data type to another and hence inter res = [ tuple ( map ( int , sub.split( ', ' ))) for sub in test_list]. Stack Exchange network consists of 177 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Converting Python 3 Data Types: Numbers, Strings, Lists, Tuples , On this page: type(), str(), int(), float(), list(), and tuple() You have seen: int (​integer), float (floating-point number), str (string), list (list), and dict (dictionary). Therefore, you will often find yourself needing to convert one data type to another​. Lists and Tuples¶. In this notebook, you will learn to store more than one valuable in a single variable. This by itself is one of the most powerful ideas in programming, and it introduces a number of other central concepts such as loops.

3. Strings, lists, and tuples, Converting Integers to Floats. Python's method float() will convert integers to floats. To use this function, add an integer inside of the parentheses:. There are various approaches to convert a tuple to a string. Approach 1 : using str.join() The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.

Comments
  • Because you're doing an assignment in the list comprehension. Get rid of x =.
  • and I assume that's not allowed? So list comprehension is not the tool for this then? I don't just want to see them in that format, I want the list to have them in that format
  • I edited my comment. But the "I'll do 6 comprehensions" doesn't make sense; they are not sufficiently faster than regular for loops to justify this kind of approach; don't pursue list comprehensions at the vast expense of sensible code
  • No, list comprehensions are perfectly fine for this. But there are no assignment statements in list comprehensions, only expressions are allowed. If you are thikning in terms of assignment, i.e. mutating state, then you shouldn't use list-comprehensions, and just use a regular for loop. But this could be a very straightforward list comprehension, no doubt
  • Why? Youve already been given a working answer.
  • I like this answer. Thanks for pointing out the usefulness of isdigit.
  • Not a bad approach, provided all of the numbery-looking strings look like positive integers. "-2" will remain a string, for example.
  • I'll give it to this one bc it's a good general solution in case anyone else has a similar problem
  • I would say isdigit is not good here. Rather, encapsulate your may_int in a function, that uses try: return int(obj) except ValueError: return obj. Or just hard-code it. Tuples should be regular.
  • @Kevin Fixed, ty
  • Yep, tlist = [(int(x[0]),x[1],int(x[2]),int(x[3]),int(x[4]),int(x[5]),int(x[6])) for x in tlist] works for me.
  • This works but hardcodes everything, including the position of the string that should not be converted.