Split a string and get the last element in Python #
Use the str.rsplit[]
method with maxsplit
set to 1
to split a string and get the last element. The rsplit[]
method splits from the right and will only perform a single split when maxsplit
is set to 1
.
Copied!
my_str = 'one,two,three,four' last = my_str.rsplit[',', 1][-1] print[last] # 👉️ 'four'
We used the rsplit[]
method to split the string from the right.
The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.
Copied!
my_str = 'one two three' print[my_str.rsplit[' ']] # 👉️ ['one', 'two', 'three'] print[my_str.rsplit[' ', 1]] # 👉️ ['one two', 'three']
The method takes the following 2 arguments:
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done, the rightmost ones [optional]
|
Except for splitting from the right, rsplit[]
behaves like split[]
.
When the maxsplit
argument is set to 1
, at most 1 split is done.
The last step is to access the last element in the list by accessing the list item at index -1
.
Copied!
my_str = 'one,two,three,four' last = my_str.rsplit[',', 1][-1] print[last] # 👉️ 'four'
You can also use the str.split[]
method in a similar way.
Copied!
my_str = 'one-two-three-four' last = my_str.split['-'][-1] print[last] # 👉️ 'four'
If your string ends with the specific separator, you might get a confusing result.
Copied!
my_str = 'one-two-three-four-' last = my_str.rsplit['-', 1][-1] # 👇️ ['one-two-three-four', ''] print[my_str.rsplit['-', 1]] print[last] # 👉️ ""
You
can use the str.strip[]
method to remove the leading or trailing separator.
Copied!
my_str = 'one-two-three-four-' last = my_str.strip['-'].rsplit['-', 1][-1] print[last] # 👉️ "four"
We used the str.strip[]
method to remove any leading or trailing hyphens from the string before calling the rsplit[]
method.
I use pandas and I have data and the data look like this
FirstName LastName StudentID
FirstName2 LastName2 StudentID2
Then I split it based on 'space' using str.split[]
So the data will look like this in DataFrame
[[FirstName, LastName, StudentID],
[FirstName2, LastName2, StudentID2]]
How to take the StudentID for every students only and save it in new column?
ZygD
16.5k37 gold badges68 silver badges88 bronze badges
asked Dec 10, 2018 at 23:55
Try the below solution:
item["x"]["y"].split[' '][-1]
0buz
3,3832 gold badges7 silver badges26 bronze badges
answered Mar 24, 2020 at 11:06
Use a list comprehension to take the last element of each of the split strings:
ids = [val[-1] for val in your_string.split[]]
answered Dec 10, 2018 at 23:57
TimTim
2,6301 gold badge14 silver badges29 bronze badges
1
You could do something like this:
import pandas as pd
data = ['FirstName LastName StudentID',
'FirstName2 LastName2 StudentID2']
df = pd.DataFrame[data=data, columns=['text']]
df['id'] = df.text.apply[lambda x: x.split[][-1]]
print[df]
Output
text id
0 FirstName LastName StudentID StudentID
1 FirstName2 LastName2 StudentID2 StudentID2
Or, as an alternative:
df['id'] = [x.split[][-1] for x in df.text]
print[df]
Output
text id
0 FirstName LastName StudentID StudentID
1 FirstName2 LastName2 StudentID2 StudentID2
answered Dec 10, 2018 at 23:58
Dani MesejoDani Mesejo
58.6k6 gold badges45 silver badges68 bronze badges
I thought I would add this simple solution which doesn't use lists or list comprehension to split an existing column/series and store the last item from the split to a new column/series in the DataFrame
import pandas as pd
data = ['FirstName LastName StudentID',
'FirstName2 LastName2 StudentID2']
df = pd.DataFrame[data=data, columns=['text']]
df['id'] = df.text.str.split[" "].str.get[-1]
Output:
index text id
0 FirstName LastName StudentID StudentID
0 FirstName2 LastName2 StudentID2 StudentID2
answered Sep 5, 2021 at 9:07
Using data frame constructor
pd.DataFrame[df.text.str.split[' '].tolist[]].iloc[:,0]
Out[15]:
0 FirstName
1 FirstName2
Name: 0, dtype: object
answered Dec 11, 2018 at 0:00
BENYBENY
307k19 gold badges153 silver badges213 bronze badges
0
Why not try a simple list comprehension
students = [
["FirstName", "LastName", "StudentID"],
["FirstName2", "LastName2", "StudentID2"]
]
print[[student[2] for student in students]]
which will print
['StudentID', 'StudentID2']
answered Dec 10, 2018 at 23:58
finefootfinefoot
8,6477 gold badges47 silver badges85 bronze badges