Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a string after a specific substring?

How can I get a string after a specific substring?

For example, I want to get the string after "world" in

my_string="hello python world, I'm a beginner" 

...which in this case is: ", I'm a beginner")

like image 663
havox Avatar asked Sep 24 '12 20:09

havox


People also ask

How do you get a string after a specific substring in Python?

Python Substring After Character You can extract a substring from a string after a specific character using the partition() method. partition() method partitions the given string based on the first occurrence of the delimiter and it generates tuples that contain three elements where.

How do you get the string after a certain character?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character. Copied! We used the String.

How do you cut a string after a specific character in Python?

To remove everything after the first occurrence of the character '-' in a string, pass the character '-' as separator and 1 as the max split value. The split('-', 1) function will split the string into 2 parts, Part 1 should contain all characters before the first occurrence of character '-'.


1 Answers

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.

like image 186
Joran Beasley Avatar answered Oct 05 '22 22:10

Joran Beasley