Python – Split string example

Python – Split string example

String is widely used in Python programming language. There are many scenarios where programmers have to split the string based on different delimiters. In this blog, we demonstrate splitting of string using different delimiters.

1) Split string using default delimiter

By default, split() method takes whitespace as delimiter.

if __name__ == '__main__':
    str = 'Code2Succeed.com - Help You Grow'
    tokens = str.split()
    for token in tokens:
        print(token)

Output

Code2Succeed.com
-
Help
You
Grow

2) Split string using delimiter other than default

You can split string other than default delimiter. Below example demonstrate splitting of string using delimiter¬†‘.'(dot).

if __name__ == '__main__':
    str = 'Code2Succeed.com - Help You Grow'
    tokens = str.split('.')
    for token in tokens:
        print(token)

output

Code2Succeed
com - Help You Grow

3) Control maximum number of tokens using split()

Using split(([sep [,maxsplit]])), you can control maximum number of tokens. Below example demonstrate controlling maximum number of tokens while spitting the string.

if __name__ == '__main__':
    str = 'Code2Succeed.com - Help You Grow'
    tokens = str.split(" ", 2)
    for token in tokens:
        print(token)

output

Code2Succeed.com
-
Help You Grow

Stay tuned for more updates and tutorials !!!

 

Leave a Reply

Your email address will not be published. Required fields are marked *