Home > Mobile >  Detect substring, then remove the rest of the string after substring including substring itself in p
Detect substring, then remove the rest of the string after substring including substring itself in p

Time:04-24

I have a string Start-Substring-abcde in python. I want to detect the presence of a substring, say -Substring. If this substring is detected, then the rest of the string will be removed, including the substring itself.

For example, Start-Substring-abcde will return Start after removing the relevant characters.

I am using python 3.9

CodePudding user response:

You can do this by try except as it is faster than if statement.

x = 'Start-Substring-abcde'
try:
    x = x[:x.index('-Substring')]
except ValueError:
    pass

This code removes the substring and the following words to the end of the string if the substring exists in the string. Otherwise it do nothing to the string.

If you want to do this with if statement you can do it this way:

x = 'Start-Substring-abcde'

if '-Substring' in x:
    x = x[:x.index('-Substring')]

print(x)

If you have any question feel free to ask.

CodePudding user response:

The first index of str.split() where you split by the substring will be the part of the initial string before the substring (if the substring does not exist in the initial string then the initial string will be returned)

in_str = 'Start-Substring-abcde'
sub_str = '-Substring'
result = in_str.split(sub_str)[0]
print(result) # 'Start'
  • Related