split a string into two strings in python

To split a string into two strings in Python, you can use the split() function. The split() function splits a string into a list of substrings based on a specified separator.

To split a string into two strings, you can specify the separator as the point where you want to split the string. For example, if you want to split a string into two at the first space character, you can use the following code:

main.py
string = "Hello World"
string1, string2 = string.split(" ", 1)
63 chars
3 lines

The split(" ", 1) function splits the string at the first space character into two substrings, and returns them as a tuple. The first substring is assigned to string1 and the second substring is assigned to string2.

You can then print the two strings to see the result:

main.py
print(string1)  # Output: "Hello"
print(string2)  # Output: "World"
68 chars
3 lines

If the separator character is not present in the string, then the original string is returned as the first substring and an empty string is returned as the second substring:

main.py
string = "HelloWorld"
string1, string2 = string.split(" ", 1)
print(string1)  # Output: "HelloWorld"
print(string2)  # Output: ""
130 chars
5 lines

related categories

gistlibby LogSnag