Split String and get the first element using 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
The syntax of
split() method is:
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.
str = 'Python is awesome' firt_element = str.split(' ',1) print(first_element) //Python
We have used the
' ' (space) as the separator.
So, here we have set
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
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) 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) print(str_split) // Python
strip(' ') method removes the leading and trailing separator (here whitespace) from the string first and then split the string.
- Check for prime number using for and while loop in Python
- Merge two dictionaries together using python (3 ways)
- Merge multiple JSON objects into one single object in Python
- Python - Check if list is empty or not
- Python - Insert an element at specific index in a list