1

Hello I am trying to remove part of a string from specific expression. For example:

string = "Hello my name is John and I would like to eat pizza"
string.removeTillTheEnd(string, "John")

now string will be Hello my name is

replace function is not enough...

heisenberg7584
  • 427
  • 9
  • 23

2 Answers2

4

How about this?

string = "Hello my name is John and I would like to eat pizza"
split_string = string.split("John", maxsplit=1)[0]

The split method on strings splits a string into a list given a seperator, and we take the first element that is found. The maxsplit argument is used to only seperate the first occurrence of "John" that it finds.

Monolith
  • 950
  • 11
  • 25
1

No need for regex or splitting into a list, just find the position and slice:

string = "Hello my name is John and I would like to eat pizza"
string = string[:string.find('John')].strip()
print(string)   # "Hello my name is"
RomanPerekhrest
  • 75,918
  • 4
  • 51
  • 91