Sobes.tech
Intern
216

How to split a string into a list of strings in Python?

Answer from AI

sobes.tech AI

# Using the split() method to split by spaces
string = "This is a string to split"
word_list = string.split()
# Result: ['This', 'is', 'a', 'string', 'to', 'split']

# Using the split() method with a delimiter
string_with_commas = "one,two,three,four"
item_list = string_with_commas.split(',')
# Result: ['one', 'two', 'three', 'four']

# Using the splitlines() method to split by newline characters
multiline_string = "Line 1\nLine 2\rLine 3\r\nLine 4"
line_list = multiline_string.splitlines()
# Result: ['Line 1', 'Line 2', 'Line 3', 'Line 4']

# Using regular expressions with re.split()
import re
string_with_delimiters = "apple,banana;orange"
split_list = re.split(r'[,;]', string_with_delimiters)
# Result: ['apple', 'banana', 'orange']

# Splitting a string into individual characters
character_list = list("abcde")
# Result: ['a', 'b', 'c', 'd', 'e']
Method Description Example usage
split() Splits a string by a specified delimiter. Defaults to spaces. string.split(',')
splitlines() Splits a string by newline characters (\n, \r, \r\n). multiline_string.splitlines()
re.split() Splits a string by a regex pattern. re.split(r'[,;]', string)
list() Converts a string into a list of its characters. list(string)