Reputation: 171
I need to replace rownum and rownum_ in "My num is rownum, your is rownum_" using placeholderdict = {rownum:20, rownum_:25}.
When I tried, it gets replaced like "My num is 20, yours is 20_
" . Expected is "My num is 20, yours is 25
"
Please share some tips.
Upvotes: 1
Views: 279
Reputation: 89
Through Formatting, you can put it in {} that you want the value there. If there is no name in {} then it will be in order, and you can also specify a value by name.
placeholderdict = {'rownum':20, 'rownum_':25}
print('My num is {rownum}, your is {rownum_}.'.format(rownum = placeholderdict.get('rownum'),
rownum_ = placeholderdict.get('rownum_')))
you can also save to value
text = 'My num is {rownum}, your is {rownum_}.'.format(rownum = placeholderdict.get('rownum'),
rownum_ = placeholderdict.get('rownum_'))
print(text)
Upvotes: 0
Reputation: 5745
You probably replaced first “rownun“ and it replaced the “rownum_” Into 20_, just change the order it will fix your issue...
text = text.replace('rownum_', placeholderdict['rownum_'])
text = text.replace('rownum', placeholderdict['rownum'])
print(text)
>>> My num is 20, yours is 25
Upvotes: 1
Reputation: 2277
You can do this:
placeholderdict = {"rownum":20, "rownum_":25}
string = "My num is rownum, your is rownum_"
string = string.replace("rownum", str(placeholderdict["rownum"]), 1)
string = string.replace("rownum_", str(placeholderdict["rownum_"]))
print(string)
Add a string.replace
and add ,1
to control the numbers of changing text. and add str()
.
And your dictionary keys have to be a string because rownum
and rownum_
is not defined.
Upvotes: 0