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()
CodePudding user response:
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())]
CodePudding user response:
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.
CodePudding user response:
Using s.split() converts a Text into a LIST.
So, use s.split(" ") splits the TEXT on whitespaces.
Then you will get:
s = "A 1 B 2.3"
print(s.split(" "))
x = s.split(" ")
for ele in x:
if ele.isalpha():
print(ele)
elif ele.isdigit():
print(int(ele))
else:
print(float(ele))
The output looks like this:
['A', '1', 'B', '2.3']
A
1
B
2.3
Thank You
CodePudding user response:
Simplest & Simplified Solution
It is easy to do it , just check the example and you will understand
mylist = [1, 2, 3, 4, 5] # creating list
result = int("".join(str(i) for i in mylist)) # making the (list --> int)
print(result) # print the result
Output :-
12345
