w3resource

Python: Split a variable length string into variables


Split Variable Length String

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

For more Practice: Solve these Related Problems:

  • Write a Python program to split a string into variables based on a specific separator.
  • Write a Python function that extracts the first three words from a long string.
  • Write a Python program to split a string into a fixed number of variables.
  • Write a Python program to extract key details from a string dynamically based on input length.

Go to:


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

Python Code Editor:

 

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.