Use a dictionary instead.

var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }

Or format with explicit numbering.

var = '{0} {0} {0}'.format('look_at_meeee')

Well, or format with named parameters.

var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')
Answer from Cat Plus Plus on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse ... Study Plan Python Interview Q&A Python Training ... The replace() method replaces a specified phrase with another specified phrase....
Discussions

Substring replace using variables as pattern and replace string
I have a file containing records with 4 values, eg: 1,Genesis,Gen,Gen 2,Eksodus,Eks,Exo 3,Levitikus,Lev,Lev 4,Numeri,Num,Num 5,Deuteronomium,Deut,Deu 6,Josua,Jos,Jos 7,Rigters,Rig,Jdg 8,Rut,Rut,Rth 9,1 Samuel,1 Sam,1Sa I need to read these into an array and I then need to read a second file ... More on discuss.python.org
๐ŸŒ discuss.python.org
6
0
January 30, 2023
python - str.replace with a variable - Stack Overflow
You currently are replacing those values with the literal name of the variable. If you want it to use the values that those variable names refer to, omit the quotes. Next, you'll have to turn those variables into strings, because I suspect that the reason you used quotes in the first place ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Replacing a variable name in text with the value of that variable - Stack Overflow
I have a template that uses placeholders for the varying content that will be filled in. Suppose the template has: "This article was written by AUTHOR, who is solely responsible for its content." ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python: Replace a string as variable in a file - Stack Overflow
If I have a file contents like this: old_string -old_string I want to change only "old_string" to be "+new_string" so the result looks like +new_string -old_string my code gives this result: + More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 24, 2017
๐ŸŒ
Reddit
reddit.com โ€บ r/godot โ€บ how to replace variables in a string with their values?
r/godot on Reddit: How to replace variables in a string with their values?
June 3, 2022 -

Hello all!

I wanted to write a simple text parser, which will take a string and replace variables encased in curly brackets with their values. I tried doing this as a test:

var user = {"name": "John", "age": 20}
var text = "Hello {name}! You are {age} years old"
var expr: RegEx = RegEx.new()
expr.compile("{([^}]+)}")
for m in expr.search_all(text):
   expr.sub(m.get_string(), String(user[m.get_string().replace('{', '').replace('}', '')]))

epr.sub gives the correct values, but how do I replace them in the original string? Is this way even efficient? (strings can get pretty long) Sorry for broken English

๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Substring replace using variables as pattern and replace string - Python Help - Discussions on Python.org
January 30, 2023 - I have a file containing records with 4 values, eg: 1,Genesis,Gen,Gen 2,Eksodus,Eks,Exo 3,Levitikus,Lev,Lev 4,Numeri,Num,Num 5,Deuteronomium,Deut,Deu 6,Josua,Jos,Jos 7,Rigters,Rig,Jdg 8,Rut,Rut,Rth 9,1 Samuel,1 Sam,1Sa I need to read these into an array and I then need to read a second file and in each record of this file replace occurrences of the 3rd field in the first file (Gen, Eks, Lev, Num, Deut etc.) with the first field (1,2,3, etc. followed by a fullstop, eg 1., 2., 3.). So i...
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ python string replace() method
Python String replace() Method - Scaler Topics
April 19, 2023 - Suppose you have written an article, ... word effectively and efficiently? In Python, there is a replace() function that helps to update the old value(character/substring) with a new value (character/substring)....
Find elsewhere
๐ŸŒ
Python Basics
pythonbasics.org โ€บ home โ€บ python basics โ€บ python string replace() method
Python String replace() Method - pythonbasics. ...
Practice now: Test your Python skills with interactive challenges ยท Define a string and call the replace() method. The first parameter is the word to search, the second parameter specifies the new value. The output needs to be saved in the string. If you don't save the output, the string variable ...
๐ŸŒ
Real Python
realpython.com โ€บ replace-string-python
How to Replace a String in Python โ€“ Real Python
October 22, 2025 - In this tutorial, you'll learn how to remove or replace a string or substring. You'll go from the basic string method .replace() all the way up to a multi-layer regex pattern using the sub() function from Python's re module.
Top answer
1 of 4
1

You could just ignore the lines which have a hyphen("-") at the beginning, and replace the rest.

The script below is a little different from yours. I have put in comments to help you understand. This should be easy to understand.

filename ="some_file"
output_filename = "some_other_file"

old_string = "old_string"
new_string = "+new_string"

input_file_handle = open(filename,"r") # File being opened in read mode
output_file_handle = open(output_filename, "w") # File being opened in write mode

# Read in input file line by line
for line in input_file_handle:

    # Write to output file and move on to next line
    if old_string not in line:
        output_file_handle.write(line+"\n")
        continue

    # This line contains the old_string. We check if it starts with "-". 
    # If it does, write original line and move on to next line
    if line.startswith("-"):
        output_file_handle.write(line+"\n")
        continue


    # At this stage we are absolutely sure we want to replace this line's contents
    # So we write the replaced version to the new file
    output_file_handle.write(new_string+"\n")


# Close both file handles
input_file_handle.close()
output_file_handle.close()
2 of 4
1

The syntax is a bit off; you'll probably want to do something more like this:

import re

test_str = ("old_string\n"
            "-old_string")

match = "old_string"
subst = "+new_string"

regex = r"^{}".format(match)

# You can manually specify the number of replacements by changing
# the 4th argument

result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix 
# the regex and u"" to prefix the test string and substitution. 

The ^ assertion in the pattern is something I recommend using, as it indicates the string to match should start at the very beginning of the line thus won't match -old_string.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 46820876
python - How do I replace a string variable - Stack Overflow
I have a code as follows with open(f1) as f: userid=f.read().replace('0', str(instance.id)) The above works well. Now, the variable userid as a string has character In will like to rep...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 36443560 โ€บ how-to-replace-variable-value-in-string-python
How to Replace variable value in string python? - Stack Overflow
Besides, if you are going to interpret the string as a Python expression, you may as well use exec() so you can just pass in locals() to use in the expression without any substitutions.
๐ŸŒ
SPSS Tutorials
spss-tutorials.com โ€บ spss-python-text-replacement-tutorial
Python Text Replacements - Simple Tutorial & Examples
May 16, 2021 - *SINGLE TEXT REPLACEMENT BY CONCATENATION. begin program python3. xVars = ['alco','cigs','exer'] for xVar in xVars: print("GRAPH/SCATTER " + xVar + " WITH COSTS.") end program. Note that we specified some SPSS variable names as a Python list holding quoted strings.
๐ŸŒ
Mimo
mimo.org โ€บ tutorials โ€บ python โ€บ how-to-replace-characters-in-a-string-in-python
How to Replace Characters in a String in Python
Replace characters in Python strings with replace() or translate(), including limits and multi-character swaps.
๐ŸŒ
Home and Learn
homeandlearn.uk โ€บ python-replace.html
The Python replace function
As long as those variables contain text, you're okay. Something we've missed out of our replace function is the count. Try this. Change String to Stringing: myOldText = "Stringing" myNewText = myOldText.replace("i", "o") print(myOldText) print(myNewText) Now you'll see Strongong printed to the output window. Every letter i has been replaced. But we'd just like the first occurrence of i to be replaced, not every occurrence. To solve the problem, the replace() function comes with an optional third parameter called count.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-string-replace
Python String replace() Method - GeeksforGeeks
July 7, 2026 - replace() method is used to replace a specified substring with another substring in a string.
๐ŸŒ
Real Python
realpython.com โ€บ videos โ€บ replace-string-python-method
Replace a String With .replace() (Video) โ€“ Real Python
00:00 To clean up the swear words ... another string. 00:15 The most basic way to replace a string in Python is to use the .replace() string method....
Published: August 22, 2023
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ replace
Python String replace()
The replace() method returns a copy of the string where the old substring is replaced with the new string.