0

I have this snippet:

s = "A 1 B 2"
a, a1, b, b1 = s.split()
a1 = int(a1)
b1 = int(b1)

I was wondering if there is anyway of unpacking and converting to int or anything else at the same time. I can also write the snippet as follows:

s = "A 1 B 2"
a, a1, b, b1 = (int(x) if i in (1, 3) else i, x for x in enumerate(s.split()))

But I wanted to know if there is a shorter version. Something like

a, int(a1), b, int(b1) = s.split()

which would make something like this also possible:

s = "A 1 B 2.3"
a, int(a1), b, float(b1) = s.split()
0

2 Answers 2

2

Assuming this is your data and datatypes:

# data and datatypes
t = 'a 1 2.4 b'
dtypes = [str, int, float, str]
a, a1, b, b1 = [dtypes[i](n) for i, n in enumerate(t.split())]
2
  • Re: "This is the shortest code you can get": 😃 I wouldn't use enumerate and access by index, but zip (and I also feel that we shouldn't construct a list), so I'd update the right hand side of your assignment to (t(x) for t, x in zip(dtypes, s.split())).
    – Manfred
    Jan 29, 2022 at 12:17
  • here manfred edited the question. Also you should consider adding your answer to a separate answer instead of a comment so it can be accepted
    – Mario
    Jan 29, 2022 at 12:36
0

You could create a "universal" converter:

def converter(s):
    """Attempts to convert to int, float or returns a string"""
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s


s = "A 1 B 3.141"

a,b,c,d = map(converter, s.split())  # apply function to all splitted things

# print values and its types
print(a, b, c, d, *map(type, (a,b,c,d)))

Output:

A 1 B 3.141 <class 'str'> <class 'int'> <class 'str'> <class 'float'>

However:

This will perform at most 3 conversion attempts per list member, you need to have exactly 4 things in your string and all in all its not very reusable. If you plug in 'A B C D' it will try 4 int conversion and 4 float conversions to get to 4 strings.

Can you do it? Yes. Should you? I have my doubts.

1
  • Did you know that exceptions are expensive in Python? Jul 15, 2022 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.