I know of only two simple ways to split a string and add into tuple
import re
1. tuple(map(lambda i: i, re.findall('[\d]{2}', '012345'))) # ('01', '23', '45')
2. tuple(i for i in re.findall('[\d]{2}', '012345')) # ('01', '23', '45')
Is there other simple ways?
I'd go for
s = "012345"
[s[i:i + 2] for i in range(0, len(s), 2)]
or
tuple(s[i:i + 2] for i in range(0, len(s), 2))
if you really want a tuple.
Usually one uses tuples when the dimensions/length is fixed (with possibly different types) and lists when there is an arbitrary number of values of the same type.
What is the reason to use a tuple
instead of a list
here?
Samples for tuples:
(x, y)
)dict
key/value-pairs (e.g. ("John Smith", 38)
)Samples for lists:
"foo|bar|buz"
splited on |
s: ["foo", "bar", "buz"]
)["-f", "/etc/fstab")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With