A python newbie question:
I would like to print in python with the c format with a list of parameters:
agrs = [1,2,3,"hello"]
string = "This is a test %d, %d, %d, %s"
How can I print using python as:
This is a test 1, 2, 3, hello
Thanks.
A python newbie question:
I would like to print in python with the c format with a list of parameters:
agrs = [1,2,3,"hello"]
string = "This is a test %d, %d, %d, %s"
How can I print using python as:
This is a test 1, 2, 3, hello
Thanks.
Strings overload the modulus operator, %
, for printf
-style formatting, and special case tuple
s for formatting using multiple values, so all you need to do is convert from list
to tuple
:
print(string % tuple(agrs))
Tuple:
Example:
print("Total score for %s is %s " % (name, score))
In your case:
print(string % tuple(agrs))
Or use the new-style string formatting:
print("Total score for {} is {}".format(name, score))
Or pass the values as parameters and print will do it:
print("Total score for", name, "is", score)
Using new-style formatting: How about these one? (just experementing here) Docs: https://docs.python.org/3.6/library/string.html
args = [1,2,3,"hello"]
string = "{}, "*(len(args)-1)+"{}" # = "{}, {}, {}, {}"
'This is a test {}'.format(string.format(*args)) # inception!
Or this one:
args = [1,2,3,"hello"]
argstring = [str(i) for i in args]
'This is a test {}'.format(', '.join(argstring))
Or simply:
args = [1,2,3,"hello"]
'This is a test {}'.format(', '.join(map(str,args)))
All print:
This is a test 1, 2, 3, hello
The % character is not needed in following method:
agrs = [1,2,3,"hello"]
print("This is a test: {:02d},{:>10d},{:05d},{:>15s}".format(agrs[0],agrs[1],agrs[2],agrs[3]))
Same will do:
agrs = [1,2,3,"hello"]
print("This is a test: {0:02d},{1:>10d},{2:05d},{3:>15s}".format(agrs[0],agrs[1],agrs[2],agrs[3]))
Each item is formatted by what follows ":" within each curly bracket, and each of those corresponds to an argument passed on in brackets to format. For example, agrs[0] is passed and the format is "02d", which is equivalent of %02d in C.
Have a look at the %
operator. It accepts a string and a tuple like that:
print "My age is %d and my favourite char is %c" % (16, '$')
l = [1,2,3,"hello"]
print("This is a test %d, %d, %d, %s"%(l[0],l[1],l[2],l[3]))
Hope this works ! Cheers bud!