w3resource

Python: Split a variable length string into variables

Python Basic: Exercise-131 with Solution

Write a Python program to split a variable length string into variables.

Sample Solution-1:

Python Code:

# Create a list of variables 'x', 'y', and 'z'.
var_list = ['a', 'b', 'c']

# Assign the first three elements of 'var_list' to 'x', 'y', and 'z'. Use [None] * 3 to ensure enough elements are available.
x, y, z = (var_list + [None] * 3)[:3]

# Print the values of 'x', 'y', and 'z'.
print(x, y, z)

# Create a new list of variables 'x' and 'y'.
var_list = [100, 20.25]

# Assign the first two elements of 'var_list' to 'x' and 'y'. Use [None] * 2 to ensure enough elements are available.
x, y = (var_list + [None] * 2)[:2]

# Print the values of 'x' and 'y'.
print(x, y)

Sample Output:

a b c                                                                                                         
100 20.25 

Pictorial Presentation:

Python: Split a variable length string into variables.

Sample Solution-2:

Python Code:

# Create a list 'var_list' containing elements 'a', 'b', 'c', 'd', and 'e'.
var_list = ['a', 'b', 'c', 'd', 'e']
# Assign each element of 'var_list' to variables 'v', 'w', 'x', 'y', and 'z' in that order.
v, w, x, y, z = var_list
# Print the values of variables 'v', 'w', 'x', 'y', and 'z'.
print(v, w, x, y, z)

Sample Output:

a b c d e

Python Code Editor:

 

Previous: Write a Python program to use double quotes to display strings.
Next: Write a Python program to list home directory without absolute path.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/python-basic-exercise-131.php