Python

Split string

Want to split a string?

To split a string, we use the method .split().

This method will return one or more new strings. All substrings are returned in the list datatype.

Note: Split with the method str.split(sep, maxsplit). The 2nd parameter is optional. If maxsplit is set, it returns no more than maxsplit elements.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

String split

We can split a string based on a character.

s = "To convert the result to"
parts = s.split(" ")
print(parts)


Result:

[‘To’, ‘convert’, ‘the’, ‘result’, ‘to’]

Any character can be used. If you want to get sentences you could use:
 
s = "Python string example. We split it using the dot character."
parts = s.split(".")
print(parts)


This will result in:
[‘Python string example’, ‘ We split it using the dot character’, ‘’]
Previous Post Next Post

Cookie policy | Privacy policy | ©