Julien Cameron
Julien Cameron

Reputation: 19

How to split a string into characters and assign each character to a separate variable

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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

Related Questions