Home > Enterprise >  Python Slicing from the last space till end of string
Python Slicing from the last space till end of string

Time:05-17

I have a string variable, something like

new_str = "8. [confusing] use python skills to slice -AB1 AB2 AAB".

I want to slice from the last letter till the end of the string. The last letter in this case should be e from the the word slice so the resulting string should be -AB1 AB2 AAB but I am not sure how to do so.

I have tried this approach new_str[new_str.rfind(' ') : ] but it slices from the last space and returns AAB.

It would be great if someone could help me with this.

CodePudding user response:

Short answer, without knowing more about the meaning of the data.

new_str.split()[-3:]

If you need a string, use:

' '.join(new_str.split()[-3:])

CodePudding user response:

The reason its printing out AAB is because the rfind method finds the last occurrence of the specified character, which in this case is the space just before AAB.

Instead you could do the following:

new_str = "8. [confusing] use python skills to slice -AB1  AB2  AAB"
print(new_str[new_str.rfind("-"):])

Output:

-AB1  AB2  AAB
  • Related