Home > Net >  Remove all characters from a string before/until a specific string variable occurs in Python
Remove all characters from a string before/until a specific string variable occurs in Python

Time:04-14

I have a string, and I want to remove all the characters before another string variable using .split(). Does anyone know how to do it?

'5 5 20-5 5.4 50/2' is my string, '20' is my variable, and I want to remove everything before 20.

CodePudding user response:

Try this:

s1 = '5 5 20-5 5.4 50/2'
s2 = '20'

new_s1 = s2   s1.split(s2, 1)[1]

Result:

'20-5 5.4 50/2'

This relies on the fact that s2 is in fact contained in s1.

Just be aware that using str.split() is definitely not the best approach here.

CodePudding user response:

Using .partition():

before, sep, after = '5 5 20-5 5.4 50/2'.partition('20')

print(before) # -> '5 5 '

print(sep) # -> '20'

print(after) # -> '-5 5.4 50/2'

CodePudding user response:

Another solution using string slicing and the index function:

s1 = '5 5 20-5 5.4 50/2'
s2 = '20'

# returns the resulting string or s1 if s2 not found in s1
print(s1[s1.index(s2):] if s2 in s1 else s1)

# result:
20-5 5.4 50/2
  • Related