Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting in python 3 without print function

Tags:

python-3.x

Trying to understand how "%s%s" %(a,a) is working in below code I have only seen it inside print function thus far.Could anyone please explain how it is working inside int()?

a=input()
b=int("%s%s" %(a,a))
like image 892
Vicky Avatar asked Sep 16 '25 19:09

Vicky


2 Answers

this "%s" format has been borrowed from C printf format, but is much more interesting because it doesn't belong to print statement. Note that it involves just one argument passed to print (or to any function BTW):

print("%s%s" % (a,a))

and not (like C) a variable number of arguments passed to some functions that accept & understand them:

printf("%s%s,a,a);

It's a standalone way of creating a string from a string template & its arguments (which for instance solves the tedious issue of: "I want a logger with formatting capabilities" which can be achieved with great effort in C or C++, using variable arguments + vsprintf or C++11 variadic recursive templates).

Note that this format style is now considered legacy. Now you'd better use format, where the placeholders are wrapped in {}.

One of the direct advantages here is that since the argument is repeated you just have to do:

int("{0}{0}".format(a))

(it references twice the sole argument in position 0)

Both legacy and format syntaxes are detailed with examples on https://pyformat.info/

or since python 3.6 you can use fstrings:

>>> a = 12
>>> int(f"{a}{a}")
1212
like image 67
Jean-François Fabre Avatar answered Sep 18 '25 09:09

Jean-François Fabre


% is in a way just syntactic sugar for a function that accepts a string and a *args (a format and the parameters for formatting) and returns a string which is the format string with the embedded parameters. So, you can use it any place that a string is acceptable.

BTW, % is a bit obsolete, and "{}{}".format(a,a) is the more 'modern' approach here, and is more obviously a string method that returns another string.

like image 27
kabanus Avatar answered Sep 18 '25 09:09

kabanus