ZR-
ZR-

Reputation: 819

Assign string elements to variables

I have some strings with 3 elements, such as '010','101'... I'm trying to assign the elements of those strings to some variables, like a,b,c. I could do that through a,b,c = "0 1 0".split(). However, if there's no spacing in my string, how can I assign those values?

Upvotes: 1

Views: 1449

Answers (4)

LeeJaeWon
LeeJaeWon

Reputation: 21

Use the index by listing it through the python list() function.

For example, Like this

k = '010'

result = list(k)
print(result[0])

If there is no criteria to distinguish such as a gap, I think the list() is more comfortable than .split().

Upvotes: 1

Ghost Ops
Ghost Ops

Reputation: 1734

You can do it just like similar to the Tuple Unpacking, like

a, b, c = '101'

Printing them will give you what you expect (in string format)

print(a, b, c, type(a))

Outputs:

1 0 1 <class 'str'>

Tell me if its not working...

Upvotes: 4

Dejene T.
Dejene T.

Reputation: 989

An efficient way to split string if no space between, add space with join method and then split example:

s = "101"

a,b,c = " ".join(s).split()

output:

#print(a, b, c)
1 0 1

Upvotes: 1

Fatemeh Mansoor
Fatemeh Mansoor

Reputation: 565

you can convert it to list

a,b,c=list('010')

Upvotes: 1

Related Questions