user3639753
user3639753

Reputation: 45

Replace multiple parameters with same value in python string formatting

I have a huge string that looks like this:

100hello100string100formatting ...

Furthermore, 100 is a dynamic value. In the original string, there are 60 occurrences of 100. How do I format the string so that I can pass the parameter only once?

I am currently doing the following:

"%dhello%dstring%dformatting%d ..." % (100, 100, 100, ...)

Is there any way to pass the value 100 only once so that it will take the same value for all other parameters?

Upvotes: 0

Views: 1437

Answers (4)

Praveen
Praveen

Reputation: 7222

I suggest using str.join.

If you have 60 occurrences of 100, that also means that you have 60 words in your string. Most likely you got those words from somewhere, for instance from a file, or from a database or from user input.

Assuming that you can get all of those words into a list, why not just join the elements of the list, instead of going to the trouble of typing all the words out?

>>> words = ['hello', 'string', 'formatting']
>>> '100'.join(words)
hello100string100formatting

For this to work, your dynamic value 100 must be a string, so if it's stored as a number, you'll need to convert it first:

>>> num = 100
>>> str(num).join(words)

Upvotes: 1

pylang
pylang

Reputation: 44545

Try string formatting (see also PEP):

"{0}hello{0}string{0}formatting".format(100)
# '100hello100string100formatting'

Upvotes: 3

H. Sodi
H. Sodi

Reputation: 550

Just a suggestion

First create a template string in which you put some special character in place where the dynamic value should be.
Example : ##hello##string##formatting

Then make a function that replace the ## in the string with given parameter using regex.

Code

def getString(value, string) :
    newString = string.replace('##', str(value))
    return newString

template = '##hello##string##formatting'
replaceHundred = getString(100, template)
replaceTwoHundred = getString(200, template)
.
.
replacedString = getString( anyValue , template)

Upvotes: -1

Adelin
Adelin

Reputation: 8219

"%dhello%dstring%dformatting" % (*[100]*3,)

Basically, you create a temp list containing the values you need ([100]), multiply that by how many times you need it (*3) and prepend that with * so that you unpack the list

Upvotes: 0

Related Questions