Split String and get the first element using python

python2 min read

Find out how to split a string and get the first element from the list using maxsplit argument in python.

In this post, we will discuss how to get the first element after we split a string into a list in python.

In Python, we can use the str.split() method with the maxsplit argument to split a string and get the first element from it. The maxsplit is set to 1 and use the index to fetch the item from the list. eg str.split('',1)[0].

The syntax of split() method is:

str.split(seperator, maxsplit)

seperator : this is the delimiter, that splits the string at the specified separator. The default is whitespace.

maxsplit : Specify the number of splits to be performed. default is -1, which means no limit.

Let's see an example to get the first element from the string.

Example:

str = 'Python is awesome' firt_element = str.split(' ',1)[0] print(first_element) //Python

We have used the ' ' (space) as the separator.

So, here we have set maxsplit to 1 which means the split()method will perform only one split.

str = 'Python is awesome' str_split = str.split(' ',1) print(str_split) // ['Python', 'is awesome']

And from the list we got the first element i.e "Python", using the index of it i.e 0 eg str.split(' ',1)[0]

Now if we a string have spaces at the beginning and the end of it. Then using maxsplit might give us an empty string as first character.

str = ' Python is awesome ' str_split = str.split(' ',1)[0] print(str_split) // " "

To fix this we have to remove the whitespaces from the start and end of the string using the strip() method like this.

str = ' Python is awesome ' str_split = str.strip(' ').split(' ',1)[0] print(str_split) // Python

The strip(' ') method removes the leading and trailing separator (here whitespace) from the string first and then split the string.

Related Topics:

How to split a list into multiple lists using python

Related Posts