Python String Search and Replace

by Remy Pereira on 08th December 2015

String operations are easy with Python's built in string methods. Most of them can be done by a simple one line of easy-to-understand code. Below are some examples with string variable str and substring variable substr.

str = "This is main string and there is hello in it."

substr = "hello"

1) Check if substring occurs within string using keyword "in"

The in keyword can check if a value is a member in a group of values. It can be used with if statements, for loops, while loops etc.

Example

if substr in str:
 print "Substring Found"

Output:

Substring Found

2) Check if substring occurs within string using "find" method

The find method can check if a substring occurs somewhere in a string. The return value of find method is index of first occurrence or -1 if not found.

Example

if str.find(substr) != -1:
 print "Substring Found at %d" %str.find(substr)

Output:

Substring Found at 33

The full syntax is:

stringname.find(substring, start, end)

The start and end arguments are optional. By default start is 0 and end is length of the string.

To search the word head between 4th and 10th characters

str.find("head", 3, 10)

3) Count the number of occurrences of substring using "count" method

The count method counts the number of matches. Example:

print "Substring Occurs %d times" %str.count(substr)

Output

Substring Occurs 1 times

The full syntax is:

stringname.find(substring, start, end)

Again the last 2 arguments are optional and default start is 0 and end is length of string.

4) Replace substring1 with substring2 using replace method

The syntax of replace method is

replace(old, new [,count]

Here the argument count is an optional argument for the number of replacements to be made. If you leave it, all occurrences will be replaced.

str = "This is main string and there is hello in it."
substr1 = "hello"
substr2 = "hola"
print "%s" %str.replace(substr1,substr2)

Output is:

This is main string and there is hola in it.

The replace method returns a copy of the string with the replacements made, but it does not actually modify the original string. If you want the original string to be changed, you have to assign the returned string to the original string.

str = str.replace(substr1,substr2)

Post a comment

Comments

Nothing yet..be the first to share wisdom.