2

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

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
Atul Arora
  • 23
  • 1
  • 3

3 Answers3

2

Try this :

>>> s = "client_user_username_type_1234567"
>>> '_'.join(s.split('_')[-2:])
'type_1234567'
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

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'
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

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.

Chayemor
  • 3,577
  • 4
  • 31
  • 54