Printing Tuple with String Formatting in Python

Printing tuple with string formatting in Python

>>> # Python 2
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

>>> # Python 3
>>> thetuple = (1, 2, 3)
>>> print(f"this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.

Python - formatting a tuple/string

While it would be simple to make a print function to print the way you want:

a = ('Surname', 'Forename', 'Payroll', 'Department', 'Salary')
def printer(tup):
print_string = str("(")
pad = 24
print_string += ", ".join(tup[:2]).ljust(pad)
print_string += ", ".join(tup[2:4]).ljust(pad)
print_string += tup[-1] + ")"
print(print_string)

>>> printer(a)
(Surname, Forename Payroll, Department Salary)

I would suggest that it would be cleaner to handle this a different way. Perhaps might I recommend taking in the values separately and then combining them in a named way. Like this

payroll = input("Enter your Payroll.") 
department = input("Enter your Department Name.")
salary = input("Enter your Salary.")
forename = input("Enter your Forename.")
surname = input("Enter your Surname.")

You can then perform which ever grouping you want and print them in a more sane manner

print("%s, %s      %s, %s     %s" % (surename, forename, .....etc)

and then you can store them in a data structure that makes sense as well

How to format strings with tuples of values like using %(name)s

I think what you're looking for is formatting strings by using the modulo operator (%s) as well as mapping format values using a dict, like this:
print('Hello, %(name)s!' % {'name': 'Jack'})

How to use list (or tuple) as String Formatting value

You don't have to spell out all the indices:

s = ['language', 'Python', 'rocks']
some_text = "There is a %s called %s which %s."
x = some_text % tuple(s)

The number of items in s has to be the same as the number of insert points in the format string of course.

Since 2.6 you can also use the new format method, for example:

x = '{} {}'.format(*s)

Python 3 - using tuples in str.format()

Pass in the tuple using *arg variable arguments call syntax:

s = "x{}y{}z{}"
tup = (1,2,3)
s.format(*tup)

The * before tup tells Python to unpack the tuple into separate arguments, as if you called s.format(tup[0], tup[1], tup[2]) instead.

Or you can index the first positional argument:

s = "x{0[0]}y{0[1]}z{0[2]}"
tup = (1,2,3)
s.format(tup)

Demo:

>>> tup = (1,2,3)
>>> s = "x{}y{}z{}"
>>> s.format(*tup)
'x1y2z3'
>>> s = "x{0[0]}y{0[1]}z{0[2]}"
>>> s.format(tup)
'x1y2z3'

Printing a tuple in Python with user-defined precision

Possible workaround:

tup = (0.0039024390243902443, 0.3902439024390244, -
0.005853658536585366, -0.5853658536585366)

print [float("{0:.5f}".format(v)) for v in tup]

Quickly formatting numbers in print() calls with tuples mixing strings and numbers

from typing import Any

def standarize(value: Any) -> str:
if type(value) == int:
return str(value)
elif type(value) == float:
return f'{value:.2f}'
else:
return str(value)

print(f'Value int: {standarize(1)}')
print(f'Value float: {standarize(113.91715)}')
print(f'Value str: {standarize("any string")}')

python string format for variable tuple lengths

Try this:

print ('%3d'*len(nums)) % tuple(nums)

Printing and formatting a tuple in python

Extract the unique values into a set, then join those into a single string:

unique = {t[0] for t in record[1]}
print '{}:{}'.format(record[0], ','.join(unique))

Demo:

>>> record = (u'U9', [(u'U2', 1.0), (u'U10', 0.6666666666666666), (u'U2', 1.0)])
>>> unique = {t[0] for t in record[1]}
>>> print '{}:{}'.format(record[0], ','.join(unique))
U9:U10,U2

Note that sets are unordered, which is why you get U10,U2 for this input, and not U2,U10. See Why is the order in dictionaries and sets arbitrary?

If order matters, convert your list of key-value pairs to an collections.OrderedDict() object, and get the keys from the result:

>>> from collections import OrderedDict
>>> unique = OrderedDict(record[1])
>>> print '{}:{}'.format(record[0], ','.join(unique))
U9:U2,U10


Related Topics



Leave a reply



Submit