简体   繁体   中英

how to get second last and last value in a string after separator in python

In Python, how do you get the last and second last element in string ? string "client_user_username_type_1234567" expected output : "type_1234567"

Try this :

>>> s = "client_user_username_type_1234567"
>>> '_'.join(s.split('_')[-2:])
'type_1234567'

You can also use re.findall :

import re
s = "client_user_username_type_1234567"
result = re.findall('[a-zA-Z]+_\d+$', s)[0]

Output:

'type_1234567'

There's no set function that will do this for you, you have to use what Python gives you and for that I present:

split slice and join

"_".join("one_two_three".split("_")[-2:])

In steps:

  1. Split the string by the common separator, "_"

    s.split("_")

  2. Slice the list so that you get the last two elements by using a negative index

    s.split("_")[-2:]

  3. Now you have a list composed of the last two elements, now you have to merge that list again so it's like the original string, with separator "_".

    "_".join("one_two_three".split("_")[-2:])

That's pretty much it. Another way to investigate is through regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM