4

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))

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ! Can I use fstrings in print function as well ? Like print (f"{a}{a}") I tried it , it gave me syntax error.
it works but from 3.6. Below version 3.6 use format instead of %
2

% 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.