As in 2.x, use str.replace().
Example:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
Answer from Ignacio Vazquez-Abrams on Stack Overflowstring - Python Replace \\ with \ - Stack Overflow
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
Using replace() method
Str.replace of a set of characters - Ideas - Discussions on Python.org
Videos
There's no need to use replace for this.
What you have is a encoded string (using the string_escape encoding) and you want to decode it:
>>> s = r"Escaped\nNewline"
>>> print s
Escaped\nNewline
>>> s.decode('string_escape')
'Escaped\nNewline'
>>> print s.decode('string_escape')
Escaped
Newline
>>> "a\\nb".decode('string_escape')
'a\nb'
In Python 3:
>>> import codecs
>>> codecs.decode('\\n\\x21', 'unicode_escape')
'\n!'
You are missing, that \ is the escape character.
Look here: http://docs.python.org/reference/lexical_analysis.html at 2.4.1 "Escape Sequence"
Most importantly \n is a newline character. And \\ is an escaped escape character :D
>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb
word1 = input("Word: ") # lets say that the given word is "tower"
word2 = "********************"
word2 = word2.replace(word[3], word[3])
print(word2)
# Now the my code replaces all the "*" characters with the character "e"
# It just prints "eeeeeeeeeeeeeeeeeeee"
# I would like the code only to replace the 4th character with the other strings 4th
# I'd like it to print "***e****************"
Hi guys, I had a quick question about the exercise I was working on.
For using the replace() method and printing the result, we have to assign it to another variable and print that new variable.
sentence = sentence.replace(‘hey’, ‘hi’) print(sentence)
But for something such as the sort method we don’t need to assign it to a new variable and just use it straight up.
list = […] list.sort() print(list)
Why is it that some methods you need to assign it to a new variable, while others work while not assigning it to a new variable and the original is changed. Thank you.
Sorry about format, I’m on mobile.