How to use string.replace() in python 3.x - python

The string.replace() is deprecated on python 3.x. What is the new way of doing this?

As in 2.x, use str.replace().
Example:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'

replace() is a method of <class 'str'> in python3:
>>> 'hello, world'.replace(',', ':')
'hello: world'

The replace() method in python 3 is used simply by:
a = "This is the island of istanbul"
print (a.replace("is" , "was" , 3))
#3 is the maximum replacement that can be done in the string#
>>> Thwas was the wasland of istanbul
# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached

You can use str.replace() as a chain of str.replace(). Think you have a string like 'Testing PRI/Sec (#434242332;PP:432:133423846,335)' and you want to replace all the '#',':',';','/' sign with '-'. You can replace it either this way(normal way),
>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> string = string.replace('#', '-')
>>> string = string.replace(':', '-')
>>> string = string.replace(';', '-')
>>> string = string.replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
or this way(chain of str.replace())
>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'

Official doc for str.replace of Python 3
official doc: Python 3's str.replace
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
corresponding VSCode's syntax notice is:
str.replace(self: str, old, new, count) -> str
Two method to use str.replace
Method 1: use builtin str's replace -> str.replace(strVariable, old, new[, count])
replacedStr1 = str.replace(originStr, "from", "to")
Method 2: use str variable's replace -> strVariable.replace(old, new[, count])
replacedStr2 = originStr.replace("from", "to")
Full demo
code:
originStr = "Hello world"
# Use case 1: use builtin str's replace -> str.replace(strVariable, old, new[, count])
replacedStr1 = str.replace(originStr, "world", "Crifan Li")
print("case 1: %s -> %s" % (originStr, replacedStr1))
# Use case 2: use str variable's replace -> strVariable.replace(old, new[, count])
replacedStr2 = originStr.replace("world", "Crifan Li")
print("case 2: %s -> %s" % (originStr, replacedStr2))
output:
case 1: Hello world -> Hello Crifan Li
case 2: Hello world -> Hello Crifan Li
screenshot:
My related (Chinese) post: 【详解】Python 3中字符串的替换str.replace

Try this:
mystring = "This Is A String"
print(mystring.replace("String","Text"))

FYI, when appending some characters to an arbitrary, position-fixed word inside the string (e.g. changing an adjective to an adverb by adding the suffix -ly), you can put the suffix at the end of the line for readability. To do this, use split() inside replace():
s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'

Simple Replace:         .replace(old, new, count) .
text = "Apples taste Good."
print(text.replace('Apples', 'Bananas')) # use .replace() on a variable
Bananas taste Good. <---- Output
print("Have a Bad Day!".replace("Bad","Good")) # Use .replace() on a string
Have a Good Day! <----- Output
print("Mom is happy!".replace("Mom","Dad").replace("happy","angry")) #Use many times
Dad is angry! <----- Output

ss = s.replace(s.split()[1], +s.split()[1] + 'gy')
# should have no plus after the comma --i.e.,
ss = s.replace(s.split()[1], s.split()[1] + 'gy')

Related

Python print split take char 5-10 for instance

I want to split string that I have.
Lets say string is hello how are you.
I want to print only the how are (meaning start after hello and finish after are
My code for now just start after the hello, but print all the rest.
Want to avoid the you.
ReadJSONFile=JSONResponseFile.read() # this is the txt file with the line
print ReadJSONFile.split('hellow',1)[1] # this gives me everything after hello
You could use string slicing:
>>> s = "hello how are you"
>>> s[6:13]
'how are'
Combine two str.split calls:
>>> s = 'hello how are you'
>>> s.split('hello', 1)[-1]
' how are you'
>>> s.split('hello', 1)[-1].split('you', 1)[0]
' how are '
>>> s.split('hello', 1)[-1].split('you', 1)[0].strip() # remove surrounding spaces
'how are'
If you have the start and end indices you can extract an slice of the string by using the slice notation:
str = 'Hello how are you"
# you want from index 6 (h) to 12 (e)
print str[6:12+1]
This should help: (Using index and slicing)
>>> start = h.index('hello')+len('hello')
>>> end =h.index('you')
>>> h[start:end].strip()
'how are'

Split off the contents of a variable after the last space in python?

I'm writing a program in python that'll split off the contents after the last space in a string. e.g. if a user enters "this is a test", I want it to return "test". I'm stuck on how to do this?
Easy and efficient with str.rsplit.
>>> x = 'this is a test'
>>> x.rsplit(None, 1)[-1] # Splits at most once from right on whitespace runs
'test'
Alternate:
>>> x.rpartition(' ')[-1] # Splits on the first actual space found
'test'
string = "this is a test"
lastWord = string.rsplit()[-1]
print lastWord
'test'
The fastest and most efficient way:
>>> "this is a test".rpartition(' ')[-1]
'test'
>>> help(str.rpartition)
Help on method_descriptor:
rpartition(...)
S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.

Strip 2m characters from string in Python

I'm trying to remove the "m2" characters from a string using python. This is the code i'm using right now. Unfortunately it appears to do nothing to the string.
Typically the string i would like to strip looks as follow; 502m2, 3m2....
if "m2" in messageContent:
messageContent = messageContent.translate(None, 'm2')
str.translate() is not the correct tool here; you are removing all m and all 2 characters regardless of their context.
If you need to remove the literal text 'm2', just use str.replace():
messageContent = messageContent.replace('m2', '')
You don't even need to test first; str.replace() will return the string unchanged if there are no instances of the literal text present:
>>> '502m2, 3m2'.replace('m2', '')
'502, 3'
>>> 'The quick brown fox'.replace('m2', '')
'The quick brown fox'
Just use str.replace
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
s = "502m2, 3m2"
print s.replace("m2","")
502, 3

Case insensitive replace

What's the easiest way to do a case-insensitive string replacement in Python?
The string type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.
>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
In a single line:
import re
re.sub("(?i)hello","bye", "hello HeLLo HELLO") #'bye bye bye'
re.sub("(?i)he\.llo","bye", "he.llo He.LLo HE.LLO") #'bye bye bye'
Or, use the optional "flags" argument:
import re
re.sub("hello", "bye", "hello HeLLo HELLO", flags=re.I) #'bye bye bye'
re.sub("he\.llo", "bye", "he.llo He.LLo HE.LLO", flags=re.I) #'bye bye bye'
Continuing on bFloch's answer, this function will change not one, but all occurrences of old with new - in a case insensitive fashion.
def ireplace(old, new, text):
idx = 0
while idx < len(text):
index_l = text.lower().find(old.lower(), idx)
if index_l == -1:
return text
text = text[:index_l] + new + text[index_l + len(old):]
idx = index_l + len(new)
return text
Like Blair Conrad says string.replace doesn't support this.
Use the regex re.sub, but remember to escape the replacement string first. Note that there's no flags-option in 2.6 for re.sub, so you'll have to use the embedded modifier '(?i)' (or a RE-object, see Blair Conrad's answer). Also, another pitfall is that sub will process backslash escapes in the replacement text, if a string is given. To avoid this one can instead pass in a lambda.
Here's a function:
import re
def ireplace(old, repl, text):
return re.sub('(?i)'+re.escape(old), lambda m: repl, text)
>>> ireplace('hippo?', 'giraffe!?', 'You want a hiPPO?')
'You want a giraffe!?'
>>> ireplace(r'[binfolder]', r'C:\Temp\bin', r'[BinFolder]\test.exe')
'C:\\Temp\\bin\\test.exe'
This function uses both the str.replace() and re.findall() functions.
It will replace all occurences of pattern in string with repl in a case-insensitive way.
def replace_all(pattern, repl, string) -> str:
occurences = re.findall(pattern, string, re.IGNORECASE)
for occurence in occurences:
string = string.replace(occurence, repl)
return string
This doesn't require RegularExp
def ireplace(old, new, text):
"""
Replace case insensitive
Raises ValueError if string not found
"""
index_l = text.lower().index(old.lower())
return text[:index_l] + new + text[index_l + len(old):]
An interesting observation about syntax details and options:
# Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
>>> import re
>>> old = "TREEROOT treeroot TREerOot"
>>> re.sub(r'(?i)treeroot', 'grassroot', old)
'grassroot grassroot grassroot'
>>> re.sub(r'treeroot', 'grassroot', old)
'TREEROOT grassroot TREerOot'
>>> re.sub(r'treeroot', 'grassroot', old, flags=re.I)
'grassroot grassroot grassroot'
>>> re.sub(r'treeroot', 'grassroot', old, re.I)
'TREEROOT grassroot TREerOot'
Using the (?i) prefix in the match expression or adding flags=re.I as a fourth argument will result in a case-insensitive match - however using just re.I as the fourth argument does not result in case-insensitive match.
For comparison:
>>> re.findall(r'treeroot', old, re.I)
['TREEROOT', 'treeroot', 'TREerOot']
>>> re.findall(r'treeroot', old)
['treeroot']
I was having \t being converted to the escape sequences (scroll a bit down), so I noted that re.sub converts backslashed escaped characters to escape sequences.
To prevent that I wrote the following:
Replace case insensitive.
import re
def ireplace(findtxt, replacetxt, data):
return replacetxt.join( re.compile(findtxt, flags=re.I).split(data) )
Also, if you want it to replace with the escape characters, like the other answers here that are getting the special meaning bashslash characters converted to escape sequences, just decode your find and, or replace string. In Python 3, might have to do something like .decode("unicode_escape") # python3
findtxt = findtxt.decode('string_escape') # python2
replacetxt = replacetxt.decode('string_escape') # python2
data = ireplace(findtxt, replacetxt, data)
Tested in Python 2.7.8
i='I want a hIPpo for my birthday'
key='hippo'
swp='giraffe'
o=(i.lower().split(key))
c=0
p=0
for w in o:
o[c]=i[p:p+len(w)]
p=p+len(key+w)
c+=1
print(swp.join(o))

Capitalize a string

Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
I would like to be able to do all string lengths as well.
>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'
#saua is right, and
s = s[:1].upper() + s[1:]
will work for any string.
What about your_string.title()?
e.g. "banana".title() -> Banana
s = s[0].upper() + s[1:]
This should work with every string, except for the empty string (when s="").
this actually gives you a capitalized word, instead of just capitalizing the first letter
cApItAlIzE -> Capitalize
def capitalize(str):
return str[:1].upper() + str[1:].lower().......
for capitalize first word;
a="asimpletest"
print a.capitalize()
for make all the string uppercase use the following tip;
print a.upper()
this is the easy one i think.
You can use the str.capitalize() function to do that
In [1]: x = "hello"
In [2]: x.capitalize()
Out[2]: 'Hello'
Hope it helps.
Docs can be found here for string functions https://docs.python.org/2.6/library/string.html#string-functions
Below code capitializes first letter with space as a separtor
s="gf12 23sadasd"
print( string.capwords(s, ' ') )
Gf12 23sadasd
str = str[:].upper()
this is the easiest way to do it in my opinion

Categories

Resources