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 OverflowUse 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')
Python 3.6 has introduced a simpler way to format strings. You can get details about it in PEP 498
>>> name = "Sam"
>>> age = 30
>>> f"Hello, {name}. You are {age}."
'Hello, Sam. You are 30.'
It also support runtime evaluation
>>>f"{2 * 30}"
'60'
It supports dictionary operation too
>>> comedian = {'name': 'Tom', 'age': 30}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
The comedian is Tom, aged 30.
Substring replace using variables as pattern and replace string
python - str.replace with a variable - Stack Overflow
python - Replacing a variable name in text with the value of that variable - Stack Overflow
Python: Replace a string as variable in a file - Stack Overflow
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
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 was because you got an error without them, as well. This is because replace takes only strings, and your variables are tuples. To fix this, cast the variable to a string.
filedata = filedata.replace('box_lat', str(box1))
If you don't want to keep the parentheses that appear in a string representation of a tuple, you can strip them off:
filedata = filedata.replace('box_lat', str(box1).strip('()'))
If you want to replace with the value of the variable box1 you need to remove the quotes surrounding it. Try:
box1 = "55, 55.7"
box2 = "-9, -7"
filedata = filedata.replace('box_lat', box1)
filedata = filedata.replace('box_lon', box2)
Quotes will replace with the text enclosed; whereas, a variable name should not be in quotes.
With Python 3.6+, you may find formatted string literals (PEP 498) efficient:
# data from @bohrax
d = {"publication": "article", "author": "Me"}
template = f"This {d['publication']} was written by {d['author']}, who is solely responsible for its content."
print(template)
This article was written by Me, who is solely responsible for its content.
Sounds like what you need is string formatting, something like this:
def get_sentence(author,pud_date):
return "This article was written by {}, who is solely responsible for its content. This article was published on {}.".format(author,pub_date)
Assuming you are parsing the variables that make up the string iteratively, you can call this function with the arguments needed and get the string returned.
That str.format() function can be placed anywhere and can take any number of arguments as long as there is a place for it in the string indicated by the {}. I suggest you play around with this function on the interpreter or ipython notebook to get familiar with it.
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()
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.