To split a string by comma in Python, you can use the Python string split() function and pass ‘,’ to get a list of strings.
string = "This,is,a,string,with,commas"
print(string.split(","))
#Output:
['This', 'is', 'a', 'string', 'with', 'commas']
You can also use the split() function from the re (regular expression) module.
import re
string = "This,is,a,string,with,commas"
print(re.split(",", string))
#Output:
['This', 'is', 'a', 'string', 'with', 'commas']
When working with strings and text in Python, the ability to manipulate and create new objects from strings can be useful.
One such situation is if you have comma characters in your strings and want to get the substrings between the comma.
To split a string by comma in Python, you can use the Python string split() function and pass ‘,’ to get a list of strings.
Below is a simple example showing you how you can use split() to split a string by comma into a list of strings.
string = "This,is,a,string,with,commas"
print(string.split(","))
#Output:
['This', 'is', 'a', 'string', 'with', 'commas']
Splitting String by Comma with re.split() Function in Python
Another way you can split a string by the comma character is to use the regular expression module split() function to perform a regular expression which will find the “,” characters and then create a list of strings.
Below is a simple example showing you how you can use re.split() to split a string by comma into a list of strings in Python.
import re
string = "This,is,a,string,with,commas"
print(re.split(",", string))
#Output:
['This', 'is', 'a', 'string', 'with', 'commas']
Hopefully this article has been useful for you to learn how to split a string by comma in Python.