python, the conversion element of the tuple

I have a line, break it down by separator. str.split (" "). How to convert 3-5 elements to int type and write to a tuple.

str="a b e 4 7 3 f h w jr  hg jjh"

that is, how to convert elements at the desired position to a certain type?

2 answers

  • answered 2018-09-21 17:34 Henry Woody

    You can check if each string element resulting from calling str.split(" ") is made of digits only, and if so, convert to int.

    Here's an example:

    string="a b e 4 7 3 f h w jr  hg jjh"
    splitted = string.split(" ")
    tuple(int(s) if s.isdigit() else s for s in splitted)
    

    With result:

    ('a', 'b', 'e', 4, 7, 3, 'f', 'h', 'w', 'jr', '', 'hg', 'jjh')
    

    Note that you should not use str as a variable name since it is reserved for the actual type str as in string.

  • answered 2018-09-21 17:38 mad_

    Find all the integers in the string using regex

    import re
    string="a b e 4 7 3 f h w jr  hg jjh"
    tuple(map(int,re.findall(r'\b(\d{1,})\b', string)))