It does work. You were just not assigning the format to a variable, and then just printing the original string. See example below:
>>> s = 'hello, {person}'
>>> s
'hello, {person}'
>>> s.format(person='james')
'hello, james' # your format works
>>> print s # but you did not assign it
hello, {person} # original `s`
>>> x = s.format(person='james') # now assign it
>>> print x
hello, james # works!
Answer from Inbar Rose on Stack Overflowpython - Format String Rounding Bug - Stack Overflow
Python string format error - Stack Overflow
Very basic string formatting not working (Python) - Stack Overflow
Is format string still an issue in Python? - Information Security Stack Exchange
a is actually slightly smaller than 1.555 due to imprecise representation of floating point values.
You can see this, for example, as follows:
f"{a:.40f}"
'1.5549999999999999378275106209912337362766'
Or,
f"{a:.64f}"
'1.5549999999999999378275106209912337362766265869140625000000000000'
One way to make it accurate is to use Decimal:
But, you could see Decimal(1.555) will output next:
>>> Decimal(1.555)
Decimal('1.5549999999999999378275106209912337362766265869140625')
Above could explain why we get the 1.55, as the 3rd number is 4.
To fix that, we should change float to str as float is not accurate.
C:\Windows\System32>python
Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal
>>> a = "1.555"
>>> float(Decimal(a).quantize(Decimal("0")))
2.0
>>> float(Decimal(a).quantize(Decimal("0.1")))
1.6
>>> float(Decimal(a).quantize(Decimal("0.01")))
1.56
>>> float(Decimal(a).quantize(Decimal("0.001")))
1.555
>>>
So, when you need accurate, consider to using Decimal.
What's performed by your snippet is binary arithmetic operation, and it require single object as second argument.
With parenthesis, you defining this argument as a two-element tuple. I added additional parenthesis to emphasise how code is interpreted.
print ("My age is %d & my name is %s, what are you ?" % (my_age, my_name))
When not, argument is single element and , %my_name is interpreted as second argument to print statement.
print evaluates each expression in turn and writes the resulting object to standard output
print ("My age is %d & my name is %s, what are you ?" % my_age), (%my_name)
Since %my_name is invalid Python expression, SyntaxError is raised.
% is an operator just like +, -, /, *, &, |, etc. Just as you can't do 4 * 5, * 6, you can't do '%s %s' % 'here', % 'there'. Actually, x % y is just a shortcut for x.__mod__(y)1. Therefore,
'%s %s' % ('here', 'there') -> '%s %s'.__mod__(('here', 'there'))
Using % twice just doesn't make sense:
'%s %s'.__mod__('here'), .__mod__('there')
1 or y.__rmod__(x) if x.__mod__() doesn't exist.
The problem here is that the format method is only being called for the final string in the 3 strings being added together. You should either apply the format operation AFTER you have concatenated the strings, or use a single string format that accepts line breaks (so you don't have to concatenate strings in the first place).
To apply after concatenation, you can just use an extra set of parentheses around the string concatenation, e.g.
print(("Here are three other numbers." + \
" First number is {0:d}, second number is {1:d}, \n" + \
"third number is {2:d}") .format(7,8,9))
Or you can use triple quotes to accept line breaks, e.g.
print("""Here are three other numbers.\
First number is {0:d}, second number is {1:d},
third number is {2:d}""" .format(7,8,9))
where \ allows a line break in the code that wont be printed.
You have a precedence issue. What you are actually doing is concatinating three strings - "Here are three other numbers.", " First number is {0:d}, second number is {1:d}, \n" and the result of "third number is {2:d}" .format(7,8,9). The format call is only applied to the third string, and therefore only replaces the {2:d}.
One way to solve this could be to surround the string concatination you intended to have with parentheses (()) so it's evaluated first:
print(("Here are three other numbers." + \
" First number is {0:d}, second number is {1:d}, \n" + \
"third number is {2:d}") .format(7,8,9))
But a much cleaner approach would be to drop the string concatination altogether and just use a multiline string (note the lack of the + operator):
print("Here are three other numbers." \
" First number is {0:d}, second number is {1:d}, \n" \
"third number is {2:d}" .format(7,8,9))
Python 3.2 does this correctly:
$ python3.2
Python 3.2.2 (default, Sep 5 2011, 22:09:30)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> sqlstring = 'INSERT INTO {}'
>>> table = 'Product'
>>> sqlstring.format(table)
'INSERT INTO Product'
>>>
What version are you using?
Additional thought:
Strings are immutable and do not self-modify in-place. Maybe you want:
sqlstring = sqlstring.format(table)
If format strings self-modified themselves in place it would be quite annoying for Python programmers, as each format string could only be used once. Sometimes we want the chance to build a nice format string then use it hundreds of times — which is easy if format() returns the result instead of modifying the format in-place.
format doesn't modify the string (it can't because strings are immutable). It returns a new string. You need to assign the result of the call to format:
result = sqlstring.format(table)
You are missing the formatter type:
%(other_id)s
Note the s after the parenthesis; you want to interpolate the values as strings. Here is a working version instead:
jQuery = ("$('#%(other_id)s').click(function() { "
" if ($(this).is(':checked')) { "
" $('#%(text_id)s').show() "
" } "
" else {"
" $('#%(text_id)s').hide()"
" }"
" });")
Dollar symbols have no meaning in %-style string formats and I've added the # id selectors for you. :-)
Personally, I would use """ triple-quotes instead:
jQuery = """\
$('#%{other_id}s').click(function() {
if ($(this).is(':checked')) {
$('#%(text_id)s').show()
}
else {
$('#%(text_id)s').hide()
}
});
"""
Better still, put this into a Jinja template anyway (since you are using Flask) and render that instead:
jquery = render_template('toggle_field.js', other_id=choice_id, text_id=text_choice_id)
where toggle_field.js is the Jinja template version of the jQuery snippet:
$('#{{ other_id }}').click(function() {
if ($(this).is(':checked')) {
$('#{{ text_id }}').show()
}
else {
$('#{{ text_id }}').hide()
}
});
Instead of code generation, consider an approach that is data-driven. Define the following two functions statically, preferably in some js file you include across all your html files:
function toggle_if_checked(checkbox, toggleable) {
var cbox = $(checkbox), tgl = $(toggleable);
tgl.toggle(cbox.is(':checked'));
}
function register_check_show_events(elist) {
var i, cboxselector, textselector;
function handler(e) {
toggle_if_checked(e.target, e.data);
}
for (i = 0; i < elist.length; i++) {
cboxselector = '#'+elist[0];
textselector = '#'+elist[1];
$(cboxselector).on('click', null, textselector, handler);
}
}
Then to register your event handlers, collect a Python list of ids and make it available to javascript via JSON.
import json
ids = [('cboxid1','textboxid1'),('cboxid2','textboxid2')]
json_ids = json.dumps(ids)
script = 'register_check_show_events({});'.format(json_ids)
In general, your code will be cleaner and easier to maintain if you only pass data between your Python and JS layers via JSON rather than generate javascript code dynamically.
I've watched recent Python videos, and even after reading some of the documentation, it is recommended to use f-string formatting rather than the older string formatting methods. Despite this, I still see lots of people using the older % formatting which is less readable, and in general takes more time to write with.
Hello, I'm trying to format else statement here. The goal is to suppress automatic new line due to print function and get a person with a single favorite language in a single sentence. When I run the code, IDLE highlights the opening quotation in the else block print statement returning "Invalid Syntax. Perhaps you forgot a comma?".
I have tried the same formatting (without else) in a practice code and it's working. I don't know what I'm doing wrong here? Also, is there any other formatting trick to get one line sentence for single favorite language?
favorite_languages = {
'jen': ['python', 'rust'],
'sarah': ['c'],
'edward': ['rust', 'go'],
'phil': ['python', 'haskell'], }
for name, languages in favorite_languages.items():
if len(languages)>1:
print(f"\n{name.title()}'s favorite languages are:")
else:
print("\n{}'s favorite language is: "format(name.title()),end='')
for language in languages:
print(f"\t{language.title()}")
You should escape literal braces by doubling them:
json_data_resp = '{{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}}'.format(activation_code, macaddress)
Excerpt from Format String Syntax:
Format strings contain “replacement fields” surrounded by curly braces
{}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{and}}.
You can do '%' for string formatting:
json_data_resp = '{"error":false,"code":"%s","mac":"%s","message":"Device configured successfully"}'%(activation_code, macaddress)