How to use string.replace() in python 3.x
As in 2.x, use str.replace()
.
Example:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
Replace \\ with \ in Python 3.x
In case you're in a python shell and just evaluated the dir, it's sufficient to print(dir)
.
Otherwise you'd want to do print(dir.replace('\\\\', '\\'))
, which seems to be a very strange output from os.getcwd()
Keep in mind that '\' is an escape character and thus needs to be escaped itself.
Here's an example from Python shell:
>>> a = 'c:\\foo\\bar'
>>> a
'c:\\foo\\bar'
>>> print(a)
c:\foo\bar
How to replace multiple substrings of a string?
Here is a short example that should do the trick with regular expressions:
import re
rep = {"condition1": "", "condition2": "text"} # define desired replacements here
# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
For example:
>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'
Python3.x: quickest way to replace characters in very large string
A more memory efficient method, that will not generate so many temporary strings along the way, would be to use str.translate
.
>>> string1 = "XYZYXZZXYZZXYZYXYXZYXZYXZYZYZXY"
>>> string1.translate({ord("X"): "A", ord("Y"): "B", ord("Z"): "C"})
'ABCBACCABCCABCBABACBACBACBCBCAB'
This will allocate just one (extra large in your case) string.
how does replace function work in python 3.x
The documentation for str.replace
says:
Return a copy of the string with all occurrences of substring old replaced by new.
From here:
There is also no mutable string type, but
str.join()
orio.StringIO
can be used to efficiently construct strings from multiple fragments.
However, it looks like, at least in the standard implementation, replace
is implemented in native code.
String replacement on a whole text file in Python 3.x?
fileinput is the module from the Python standard library that supports "what looks like in-place updating of text files" as well as various other related tasks.
for line in fileinput.input(['thefile.txt'], inplace=True):
print(line.replace('old stuff', 'shiny new stuff'), end='')
This code is all you need for the specific task you mentioned -- it deals with all of the issues (writing to a different file, removing the old one when done and replacing it with the new one). You can also add a further parameter such as backup='.bk'
to automatically preserve the old file as (in this case) thefile.txt.bk
, as well as process multiple files, take the filenames to process from the commandline, etc, etc -- do read the docs, they're quite good (and so is the module I'm suggesting!-).
Python string.replace, only replace under certain circumstances
text = '1 x Sandwich, "2 x Coffee, with cream", 1 x Apple pie'
def comma_changer(text):
text = list(text)
quote_counter = 0
for i,char in enumerate(text):
if char == '"':
quote_counter+=1
elif char == ",":
if quote_counter%2 == 1:
text[i] = ":"
return("".join(text))
comma_changer(text) #'1 x Sandwich, "2 x Coffee: with cream", 1 x Apple pie'
Related Topics
Find Full Path of the Python Interpreter
Getting Realtime Output Using Subprocess
What Exactly Is a "Raw String Regex" and How to Use It
Weird Timezone Issue with Pytz
How to Remove Convexity Defects in a Sudoku Square
What Does "Hashable" Mean in Python
Simple Prime Number Generator in Python
Find the Most Common Element in a List
How to Tail a Log File in Python
How to Preserve Timezone When Parsing Date/Time Strings with Strptime()
How to Use String.Replace() in Python 3.X
Imploding a List for Use in a Python MySQLdb in Clause
How to Get List of Values from Dict
Http Requests and JSON Parsing in Python
Pytest - Specify Log Level from the Cli Command Running the Tests