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.
1 2 3 4 5 |
if __name__ == '__main__': str = 'Code2Succeed.com - Help You Grow' tokens = str.split() for token in tokens: print(token) |
Output
1 2 3 4 5 |
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).
1 2 3 4 5 |
if __name__ == '__main__': str = 'Code2Succeed.com - Help You Grow' tokens = str.split('.') for token in tokens: print(token) |
output
1 2 |
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.
1 2 3 4 5 |
if __name__ == '__main__': str = 'Code2Succeed.com - Help You Grow' tokens = str.split(" ", 2) for token in tokens: print(token) |
output
1 2 3 |
Code2Succeed.com - Help You Grow |
Stay tuned for more updates and tutorials !!!