Inserting the Same Value Multiple Times When Formatting a String

Inserting the same value multiple times when formatting a string

You can use advanced string formatting, available in Python 2.6 and Python 3.x:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

Is there a way to format one string multiple times in Python?

You can have any level of formatting depending on the number of braces

>>> template = '{general_setting} ... {{specific_setting}}'.format(general_setting='general')
>>> my_string = template.format(specific_setting='specific')
>>> print (my_string)
general ... specific

Insert Repeated Variables into String

Use positional argument specifier in format:

>>> '{0} {0}, {1}!'.format('hello', 'world')
'hello hello, world!'
>>>

Python string formatting: reference one argument multiple times

"{0} {1} {1}".format("foo", "bar")

How to format a String multiple times?

You can do this in one statement by using a Locale that uses a , as the decimal separator (e.g. Locale.GERMANY), and specifying the width format option:

double price = 20.2;
String formatted = String.format(Locale.GERMANY, "%10.2f", price);
System.out.println(formatted);

Output:

     20,20

See the format string syntax for details.

Refer to the same parameter multiple times in a fmt.Sprintf format string

Package fmt

import "fmt" 

Explicit argument indexes:

In Printf, Sprintf, and Fprintf, the default behavior is for each
formatting verb to format successive arguments passed in the call.
However, the notation [n] immediately before the verb indicates that
the nth one-indexed argument is to be formatted instead.


You can pass the variable v once. For example,

package main

import "fmt"

func getTableCreationCommands(s string) string {
return fmt.Sprintf(`
CREATE TABLE share_%[1]v PARTITION OF share FOR VALUES IN (%[1]v);
CREATE TABLE nearby_%[1]v PARTITION OF nearby FOR VALUES IN (%[1]v);
`, s)
}

func main() {
fmt.Println(getTableCreationCommands(("X")))
}

Playground: https://play.golang.org/p/fKV3iviuwll

Output:

CREATE TABLE share_X PARTITION OF share FOR VALUES IN (X);
CREATE TABLE nearby_X PARTITION OF nearby FOR VALUES IN (X);

Can I repeat a string format descriptor in python?

You can repeat the formatting string itself:

print ('{:5d} '*5).format(*values)

Format string is a normal string, so you can multiply it by int

>>> '{:5d} '*5
'{:5d} {:5d} {:5d} {:5d} {:5d} '


Related Topics



Leave a reply



Submit