In Python 2.7.1 I can create a named tuple:
from collections import namedtuple
Test = namedtuple('Test', ['this', 'that'])
I can populate it:
my_test = Test(this=1, that=2)
And I can print it like this:
print(my_test)
Test(this=1, that=2)
but why can't I print it like this?
print("my_test = %r" % my_test)
TypeError: not all arguments converted during string formatting
Edit:
I should have known to look at Printing tuple with string formatting in Python
Since my_test is a tuple, it will look for a % format for each item in the tuple. To get around this wrap it in another tuple where the only element is my_test:
print("my_test = %r" % (my_test,))
Don't forget the comma.
You can do this:
>>> print("my_test = %r" % str(my_test))
my_test = 'Test(this=1, that=2)'
It's unpacking it as 2 arguments. Compare with:
print("dummy1 = %s, dummy2 = %s" % ("one","two"))
In your case, try putting it in a tuple.
print("my_test = %r" % (my_test,))
The earlier answers are valid but here's an option if you don't care to print the name. It's a one-liner devised to pretty print only the contents of a named tuple of arbitrary length. Given a named tuple assigned to "named_tuple" the below yields a comma-delineated string of key=value pairs:
', '.join(['{0}={1}'.format(k, getattr(named_tuple, k)) for k in named_tuple._fields])
As now documented at 4.7.2. printf-style String Formatting, the % string formatting or interpolation operator is problematic:
The [printf-style string formatting operations] exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors
So for example you can now do:
from collections import namedtuple
Test = namedtuple('Test', ['this', 'that'])
my_test = Test(this=1, that=2)
print("my_test = {0!r}".format(my_test))
Related
What is the difference between defining a variable and using it in a string and putting %s in a string and passing in the value after?
site = "Stackoverflow"
site + " is great!"
"%s is great!" % "Stackoverflow"
Printing either of these gives the same result so when is it better to use one over the other?
If you want to keep certain string constants in the same file, or on the top most of the file, you can declare the string with the placeholders as constants, then replace the placeholders with actual variable at run time through the % syntax.
This also allows greater re-usability.
Eg. you can store a single constant "%s is %s years old".
Using this syntax might also make the string more readable.
For two strings, there is little difference.
For multiple strings, s1 + s2 + s3 is less efficient, as it has to create a temporary str object for the first concatenation, where as both "%s %s %s" % (s1, s2, s3) and "{} {} {}".format(s1, s2, s3) creates the final str object immediately.
One:
'string' + 'string'
Two:
'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')
There is a great article on this here: https://pyformat.info/
Also the docs are a great resource: https://docs.python.org/2/library/string.html#format-string-syntax
Version one is less efficient with larger amounts of concatenation.
I have the following python code:
def plot_only_rel():
filenames = find_csv_filenames(path)
for name in filenames:
sep_names = name.split('_')
Name = 'Name='+sep_names[0]
Test = 'Test='+sep_names[2]
Date = 'Date='+str(sep_names[5])+' '+str(sep_names[4])+' '+str(sep_names[3])
plt.figure()
plt.plot(atb_mat_2)
plt.title((Name, Test, Date))
However when I print the title on my figure it comes up in the format
(u'Name=X', u'Test=Ground', 'Date = 8 3 2012')
I have the questions:
Why do I get the 'u'? Howdo I get rid of it along with the brackets and quotation marks?
This also happens when I use suptitle.
Thanks for any help.
plt.title receives a string as it's argument, and you passed in a tuple (Name, Test, Date). Since it expects a string it tried to transform it to string using the tuple's __str__ method which gave you got output you got. You probably want to do something like:
plat.title('{0} {1}, {2}'.format(Name, Test, Date))
How about:
plt.title(', '.join(Name,Test,Date))
Since you are supplying the title as an array, it shows the representation of the array (Tuple actually).
The u tells you that it is an unicode string.
You could also use format to specify the format even better:
plt.title('{0}, {1}, {2}'.format(Name, Test, Date))
In Python > 3.6 you may even use f-string for easier formatting:
plt.title(f'{Name}, {Test}, {Date}')
I'd like to add to #Gustave Coste's answer: You can also use lists directly in f-strings
s="Santa_Claus_24_12_2021".split("_")
print(f'Name={s[0]}, Test={s[1]}, Date={s[2]} {s[3]} {s[4]}')
result: Name=Santa, Test=Claus, Date=24 12 2021. Or for your case:
plt.title(f'Name={sep_names[0]}, Test={sep_names[2]}, Date={sep_names[5]} {sep_names[4]} {sep_names[3]}')
How do I replace %s with a defined/non-empty variable string? Or rather what is the Pythonic or syntactic sugar for doing so?
Example:
# Replace %s with the value if defined by either vehicle.get('car') or vehicle.get('truck')
# Assumes only one of these values can be empty at any given time
# The get function operates like http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get
logging.error("Found duplicate entry with %s", vehicle.get('car') or vehicle.get('truck'))
I think you want this:
'Found duplicate entry with %s' % (vehicle.get('car') or vehicle.get('truck'))
This will replace the '%s' with the non-empty string (assuming only one is non-empty). If both contain text, it will be replaced with the output of vehicle.get('car')
You could also use this type of string formatting:
'Found duplicate entry with {0}'.format(vehicle.get('car') or vehicle.get('truck'))
This will return the same result.
Have you tried something like this?
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck')))
Or if truck is also empty, you can return a default value:
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck', 'default')))
I use Python/MySQLdb frequently and often format a list of categories for MySQL. The below code turns a list of categories into 'ADD COLUMN a FLOAT, ADD COLUMN b FLOAT, ADD COLUMN c FLOAT'. I want to figure out how best to simplify this piece of code, allowing for arbitrary change to generic string 's' (e.g. 'ADD COLUMN %s FLOAT' could easily be '%s = %d' or "%s = '%s'"). Is there some form of list comprehension which works?
categories = ['a','b','c']
select_l = []
for cat in categories:
s = 'ADD COLUMN %s FLOAT' % (cat)
select_l.append(s)
select_s = ", ".join(select_l)
I could create a method, but there seems to many examples where it wouldn't handle a specific need. Thanks
Using a generator expression, this can be written as a one-liner:
select_s = ", ".join('ADD COLUMN %s FLOAT' % cat for cat in categories)
I writing HTML to a text file which is then read by the browser, but I get an error stating "not all arguments converted during string formatting"
But i can't see hwere im going wrong.
z.write('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>' % k)
You're missing parentheses:
z.write(('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>') % k)
But it would be better not to mix concatenation and formatting. So consider:
'<td><a href=/Plone/query/species_strain?species=%(k)s>%(k)s</td>' % {'k': k}
You might want to generate HTML using a dedicated tool. Concatenating strings tends to lead to buggy and hard to parse HTML.
You're using string concatenation in combination with substitution. Your substitution formatter %s is in the first string, but the % k applies to the last. You should do this:
'<td><a href=/Plone/query/species_strain?species=%s>%s</td>' % (k,k)
Or this:
('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>') % k
You get wrong and combining + and string formatting through %. If k contains any %-sequence it would look like this:
'<td...species=%s>...%s...</td>' % k
You get two or more %-sequences and only one argument. You probably want this instead:
'...species=%s>%s</td>' % (k, k)
% k must be after string with %s
z.write('<td><a href=/Plone/query/species_strain?species=%s>' % k +k+'</td>')
or better
z.write('<td><a href=/Plone/query/species_strain?species=%s>%s</td>' % (k, k))