How to Split a String into Two Variables in Python?

Estimated read time 1 min read

To split a string into two variables in Python, you can use the split() method, which splits a string at a specified separator and returns a list of substrings. If you know that the string contains exactly two substrings separated by a specific character, you can use split() to split the string into two variables. Here’s an example of how to split a string into two variables:

# define the string to be split
my_string = 'apple,orange'

# use split() to split the string into two variables
var1, var2 = my_string.split(',')

# print the variables
print(var1)
print(var2)

In this example, we first define the string we want to split, which is ‘apple,orange’. We use the split() method to split the string into two variables, var1 and var2, at the comma separator.

Finally, we print the two variables to verify that the string has been split correctly. In this example, the output is:

apple
orange

Note that if the string contains more than two substrings separated by the same separator, this method will not work as expected. In that case, you may need to use a different method to split the string into the desired variables.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply