Home > Software engineering >  Assign string elements to variables
Assign string elements to variables

Time:11-07

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?

CodePudding user response:

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...

CodePudding user response:

you can convert it to list

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

CodePudding user response:

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

CodePudding user response:

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().

  • Related