The easiest way is probably just to split on your target word
my_string="hello python world , i'm a beginner"
print(my_string.split("world",1)[1])
split takes the word (or character) to split on and optionally a limit to the number of splits.
In this example, split on "world" and limit it to only one split.
Answer from Joran Beasley on Stack OverflowThe easiest way is probably just to split on your target word
my_string="hello python world , i'm a beginner"
print(my_string.split("world",1)[1])
split takes the word (or character) to split on and optionally a limit to the number of splits.
In this example, split on "world" and limit it to only one split.
I'm surprised nobody mentioned partition.
def substring_after(s, delim):
return s.partition(delim)[2]
s1="hello python world, I'm a beginner"
substring_after(s1, "world")
# ", I'm a beginner"
IMHO, this solution is more readable than @arshajii's. Other than that, I think @arshajii's is the best for being the fastest -- it does not create any unnecessary copies/substrings.
Videos
Hi All
I am trying to extract the year from the below column on Python.
I cannot use the partition method & split function as it does not seems to exist for me.
Any idea how else can I extract only the years
My Python version is 3.10.4
Hello,
I want to remove the entire substring after a particular word in Python.
For instance, if the word is "Excerpt," all text after the word would be removed.
However, my code is not accomplishing that task.
If the word exists in the string, I would find the index of it.
After that, I would subtract the len(text)-index of the word, which should point to the word.
Am I not returning from 0-index of the word, hence removing the word, and everything after the word.
What is the issue with my code?
str1 = 'Excerpt'
if str1 in text.split():
strLength = text.find(str1)
a = text[0:len(text)-strLength]
print(a)