Reputation: 19
I need to split a 4-digit string number into 4 1-digit strings.
The number looks like this: num = "1234"
I need so split it to separate variables: a = "1"
, b = "2"
, c = "3"
, and d = "4"
, so I can later reform it as: print (str(a) + ',' + str(b) + str(c) + str(d))
.
P.S. please don't tell me how to add a comma between "a" and "b", I need the variables for later.
Upvotes: 1
Views: 667
Reputation: 476669
You can use iterable unpacking:
a, b, c, d = num
given these are strings. But usually it is better to use a list, since then you can handle strings with arbitrary length:
chars = list(num)
This works since a string is an iterable of characters. So you can unpack them with iterable unpacking, or use the list
constructor, which takes an iterable and creates a list with the elements of the iterable.
Upvotes: 8