-2

I want to slice string up to last occurrence of a specific character:

Example:

From the text "xxx.yyy.zzz" I want only "xxx.yyy"

From the text "xxx.xxx.yyy.xyzxzy" I want "xxx.xxx.yyy"

where I want to slice up to the last occurrence of ".".

cigien
  • 57,834
  • 11
  • 73
  • 112
Matix
  • 32
  • 7

2 Answers2

4

Just use str.rsplit

"xxx.yyy.zzz".rsplit('.', 1)[0]
'xxx.yyy'

"xxx.xxx.yyy.xyzxzy".rsplit('.', 1)[0]
'xxx.xxx.yyy'
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
-1

print(s[:-s[::-1].find('.') - 1])

Jenfi
  • 1
  • s = 'your.string.123123.1312312.313' – Jenfi Apr 11 '22 at 14:24
  • This will work, but imagine seeing this line of code again in a year time: you'll have no idea what it does from just reading it. It could be more 'pythonic': "clear, concise and maintainable", as nicely explained in this answer: https://stackoverflow.com/a/25011492/1282144 – Jasper Apr 11 '22 at 15:01