anderssinho anderssinho - 6 months ago 28
Python Question

Replace special character in string

I'm having a issue with a problem where I want to replace a special character in a text-file that I have created with a string that I defined.

This is a guess the number game.
import datetime, random
from random import randint

fileOpen = open('text.txt','r')
savedData =
#print (savedData)

now =
date = now.strftime("%Y-%m-%d")
date = str(date)
time = now.strftime("%H:%M")
time = str(time)

savedData.replace(";", date)
print (savedData)

I have tried with something that looks like this. I thought I could just read from the file, save it's content in my own string and then use the
function to alter the string.
But when I try to do the last print, noting has happened with the
string. What am I doing wrong?

The text-file just looks like this, all is on one line:

Today it's the ; and the time is (. I'm feeling ) and : is todays lucky number. The unlucky number of today is #

Jim Jim

str.replace doesn't alter the string in place, no string operations do because strings are immutable. It returns a copy of the replaced string which you need to assign to another name:

replacedData = savedData.replace(";", date)

now your replaced string will be saved to the new name you specified in the assignment.