Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace part of a string in Python?

Tags:

python

string

I used regular expressions to get a string from a web page and part of the string may contain something I would like to replace with something else. How would it be possible to do this? My code is this, for example:

stuff = "Big and small" if stuff.find(" and ") == -1:     # make stuff "Big/small" else:     stuff = stuff 
like image 455
Markum Avatar asked Apr 06 '12 00:04

Markum


People also ask

How do you replace only one occurrence of a string in Python?

>>> help(str. replace) Help on method_descriptor: replace(...) S. replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

How do you replace a specific part of a string in Python?

replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.

How do you replace one character in a string in Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).

How do you replace a specific part of a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.


2 Answers

>>> stuff = "Big and small" >>> stuff.replace(" and ","/") 'Big/small' 
like image 122
jamylak Avatar answered Sep 28 '22 12:09

jamylak


Use the replace() method on string:

>>> stuff = "Big and small" >>> stuff.replace( " and ", "/" ) 'Big/small' 
like image 30
Russell Borogove Avatar answered Sep 28 '22 11:09

Russell Borogove