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]}')
Related
I'm coming into Python3 after spending time with Ruby, R, and some Java. Immediately I've come across the format() function and I'm a little lost as to what it does. I've read Python | format() function and see that it somehow resembles this in ruby:
my_name = "Melanie"
puts "My name is #{my_name}."
Outputs:
"My name is Melanie."
However, I don't understand why I can't just use a variable as above. I must be very much misunderstanding the usage of the format() function. (I'm a novice, please be gentle.)
So what does format() actually do?
You can definitely use a variable in the string example that you have shown, in the following manner:
my_name = "Melanie"
Output = "My name is " + my_name + "."
print(Output)
My name is Melanie.
This is the easy way, but not the most elegant.
In the above example, I have used 3 lines and created 2 variables (my_name and Output)
However, I can get the same output using just one line of code and without creating any variables, using format()
print("My name is {}.".format("Melanie"))
My name is Melanie.
Curly braces {} are used as placeholders, and the value we wish to put in the placeholders are passed as parameters into the format function.
If you have more than one placeholder in the string, python will replace the placeholders by values, in order.
Just make sure that the number of values passed as parameters to format(), is equal to the number of placeholders created in the string.
For example:
print("My name is {}, and I am {}.".format("Melanie",26))
My name is Melanie, and I am 26.
There are 3 different ways to specify placeholders and their values:
Type 1:
print("My name is {name}, and I am {age}.".format(name="Melanie", age=26))
Type 2:
print("My name is {0}, and I am {1}.".format("Melanie",26))
Type 3:
print("My name is {}, and I am {}.".format("Melanie",26))
Additionally, by using format() instead of a variable, you can:
Specify the data type, and
Add a formatting type to format the result.
For example:
print("{0:^7} has completed {1:.3f} percent of task {2}".format("Melanie",75.765367,1))
Melanie has completed 75.765 percent of task 1.
I have set the data type for the percentage field to be a float, with 3 decimals, and given a character length of 7 to the name, and center-aligned it.
The alignment codes are:
' < ' :left-align text
' ^ ' :center text
' > ' :right-align
The format() method is helpful when you have multiple substitutions and formattings to perform on a string.
The format function is a method for string in python, it is use to add a variable to string. for example:
greetings = 'hello {0}'
visitor = input('please enter your name')
print(greetings.format(visitor))
it can also be use to pad/position string also, thisn actually align the visitor into to the greetings in 10 byte of space
greetings = 'hello {0:^10}'
visitor = input('please enter your name')
print(greetings.format(visitor))
Also, there are two type of format in python 3x: the format expression and the format function.
the format expression is actually this '%'
and many more on 'format'. Maybe you should check on the doc 'format' by typing "help(''.format)"
An example using the format function is this:
name = Arnold
age = 5
print("{ }, { }".format(name, age))
This displays:
Arnold, 5
How can I add space as parameter in string in python
For example,
If I write:
s="test"
print(f" {s:< 5}{s}")
Then
test test
I want something that
w=5
printf(f" {s:<f'{w}'}{s}")
Try this:
s = "test"
w = 5
print(f" {s:<{w}}{s}")
This should produce the same result as:
print(f" {s:<5}{s}")
If I have well understood, you want to print w spaces.
You could do something like : print(f"{s:<{w}}{s}")
Else, there is also the method ljust :
print(s.ljust(w, " ")+s)
Instead Try This:
print(f"{s:<{w}{s}")
Printf() is nothing in python until you define function named printf() manually. And You can't initialise format specifier inside format specifier.
What I want to achieve
value = 'a.b.c.d.e'
new_value = value.split('.')
new_value[-1] = F
''.join(new_value)
Now I would like to achieve this in one line. something like below
''.join(value[-1] = F in value.split('.'))
my above expression throws error because it is kind of wrong so is there a possible way to achieve this
Value should be "1.2.3.4.5" and join doesn't work for int. You should use new_value[-1]='10' instead.
''.join(value.split('.')[:-1]+['10'])
Recently, I found ''.format function very useful because it can improve readability a lot comparing to the % formatting.
Trying to achieve simple string formatting:
data = {'year':2012, 'month':'april', 'location': 'q2dm1'}
year = 2012
month = 'april'
location = 'q2dm1'
a = "year: {year}, month: {month}, location: {location}"
print a.format(data)
print a.format(year=year, month=month, location=location)
print a.format(year, month, location)
Whilst two first prints do format as I expect (yes, something=something looks ugly, but that's an example only), the last one would raise KeyError: 'year'.
Is there any trick in python to create dictionary so it will automatically fill keys and values, for example somefunc(year, month, location) will output {'year':year, 'month': month, 'location': location}?
I'm pretty new to python and couldn't find any info on this topic, however a trick like this would improve and shrink my current code drastically.
Thanks in advance and pardon my English.
The first print should be
print a.format(**data)
Also, if you are finding some shortcuts, you could write one like, no big difference.
def trans(year, month, location):
return dict(year=year, month=month, location=location)
data = {'year':2012, 'month':'april', 'location': 'q2dm1'}
a = "year: {year}, month: {month}, location: {location}"
print a.format(**data)
..is what you are looking for. It's functionally identical to doing .format(year=data['year'], ...), or the other examples you gave.
The double-asterix thing is a hard thing to search for, so it's usually referred to as "kwargs". Here's a good SO question on this syntax
You can use the dict() callable:
dict(year=yeah, month=month, location=location)
When passing keyword arguments it creates a dict containing the elements you specified as kwargs.
If you do not want to specify the argument names, use the positional style of .format():
>>> a = 'year {0} month {1} location {2}'
>>> print a.format(2012, 'april', 'abcd')
year 2012 month april location abcd
However, if you try to do something similar to what compact() in PHP does (create a dict mapping variable names to its values without specifying name and variable separately), please don't. It just results in ugly unreadable code and would require nasty hacks anyway.
You could pass locals():
a.format(**locals())
Of course, this has issues: you will have to pass everything in locals, and it can be difficult to understand the effect of renaming or removing a variable.
A better way would be:
a.format(**{k:v for k,v in locals() if k in ('year', 'month')})
# or; note that if you move the lambda expression elsewhere, you will get a different result
a.format(**(lambda ld = locals(): {k:ld[k] for k in ('year', 'month')})())
But this is not any more concise, unless you wrap it up with a function (which must of course take a dict parameter).
As of Python 3.6, you can also use the new Formatted string literals (f-strings), which you can use with variables:
year = 2012
month = 'april'
location = 'q2dm1'
a = f"year: {year}, month: {month}, location: {location}"
print(a)
or a dictionary:
data = {'year': 2012, 'month': 'april', 'location': 'q2dm1'}
a = f"year: {data['year']}, month: {data['month']}, location: {data['location']}"
print(a)
Note the f prefix before the string literal.
PEP 498: Formatted string literals:
Formatted string literals are prefixed with 'f' and are similar to the
format strings accepted by str.format(). They contain replacement
fields surrounded by curly braces. The replacement fields are
expressions, which are evaluated at run time, and then formatted using
the format() protocol:
>>>
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
...
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))