Home > Back-end >  Replacing part of a string with strings in a list
Replacing part of a string with strings in a list

Time:05-20

I have a text file that has a couple of square brackets [] that represent sections of the text that need to be replaced. I also have a list of strings that I would like to use to replace the text in the text file. my list of words would be:

inputs = ["John", "Friday", "Kyle"]
words = ["name", "day", "name"]

What happens when more than 1 of the strings is the same in the list?

For example: "Hello, my name is [name]. Tomorrow will be [day].

I would like the text to read as the following: "Hello, my name is John. Tomorrow will be Friday.

This is what I'm trying to make work

f = open(file_name, 'r')

lib_lines = f.readlines()
for index,line in enumerate(lib_lines):
    re.sub(words[index], inputs[index], line)
file_contents = f.read()

print (file_contents)

CodePudding user response:

string.replace("before", "after")

so if you want to replace "[name]" in the string with "John" do

file_contents.replace("[name]", "John")

if these are stored in a list then do

neatString = file_contents.replace(f"[{words[0]}]", inputs[0])

if you want to loop and get all the words automatically:

neatString = file_contents
for i, word in enumerate(words):
    neatString = neatString.replace(f"[{words[i]}]", inputs[i])

CodePudding user response:

Here's one way to do it:

from io import StringIO

inputs = ["John", "Friday"]
words = ["name", "day"]


in_file = StringIO("""
Hello, my name is [name].

Tomorrow will be [day].
""".strip())

# with open(file_contents) as in_file:
file_contents = in_file.read()

for word, repl in zip(words, inputs):
    file_contents = file_contents.replace(f'[{word}]', repl)

# write file contents to file-like object
out_file = StringIO()
out_file.write(file_contents)

# read in new contents
out_file.seek(0)
print(out_file.read())

Output:

Hello, my name is John.

Tomorrow will be Friday.

CodePudding user response:

As mentioned string.replace("[name]", "John") would be easier

I would recommend to use a dict though, there are quiet easy to use too and doesn't need to be in order and use an index to be replaced.

dict  = {'[name]': 'John', '[day]': 'Friday'}

str = "Hello, my name is [name]. Tomorrow will be [day]."

for key, value in dict.items():
    str = str.replace(key, value);

print(str);
# output :  Hello, my name is John. Tomorrow will be Friday.

It would change each key by the value in the string you give so if you have multiple occurence of [name] it will change all of theim.

dict  = {'[name]': 'John', '[day]': 'Friday'}

str = "Hello, my name is [name]. Tomorrow will be [day]. And my name is still [name]"

for key, value in dict.items():
    str = str.replace(key, value);

print(str); 
# output :  Hello, my name is John. Tomorrow will be Friday. And my name is still John
  • Related