in python how to split a string

Published on Aug. 22, 2023, 12:15 p.m.

To split a string in Python, you can use the split() method. This method splits a string into a list of substrings based on a specified delimiter. Here’s an example:

my_string = "Hello, world!"
my_list = my_string.split(", ")
print(my_list)

In this example, the split() method is used to split the my_string variable into a list of substrings based on the comma and space delimiter. The resulting my_list will contain two strings: Hello and world!.

If no delimiter is specified, the split() method will split a string into a list of substrings using whitespace as the default delimiter. Here’s an example:

my_string = "Hello world!"
my_list = my_string.split()
print(my_list)

In this example, the split() method is used to split the my_string variable into a list of substrings based on whitespace. The resulting my_list will also contain two strings: Hello and world!.

Tags:

related content