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
  • 563
  • 2
  • 10
  • 30

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
  • 1,067
  • 1
  • 13
  • 29
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
  • 88,541
  • 4
  • 65
  • 105