I am using Python 3.3.2 and I am trying to set the number of decimals after an arithmetic operation but it keeps throwing me SyntaxError: invalid syntax. I can't seem to figure out where I am going wrong. Thanks!
exampleInt = 123.456789
print({:.2f}.format(exampleInt)
I keep getting the error at the colon from the Python shell.
:.2f is not a valid literal. You want a format string, and string literals need quotes:
In [1]: exampleInt = 123.456789
In [2]: print('{:.2f}'.format(exampleInt))
123.46
Also, Delgan is right and a closing parenthesis is missing in your example, but the Python shell will just continue the line in this case, rather than raise a SyntaxError.
You forgot to close the print parenthesis, right?
Related
I'm using a format() in python and I want to use a variable pokablelio so that the person could choose how many numbers to output after the dot. When I try to put the variable alone after the comma it outputs: ValueError: Invalid format specifier. I tried replacing some characters or making the whole string in a parentheses but that didn't work.
Right now I'm wondering: Can I even use a variable as a string to put it in format's place?
(note: The machine should have a "'.10f'" string in the variable)
Error and the code
It is possible to use variables as part of the format specifier, just include them inside additional curly braces:
>>> n_places = 10
>>> f'{1.23:.{n_places}f}'
'1.2300000000'
This question already has answers here:
How to use digit separators for Python integer literals?
(4 answers)
Closed 3 years ago.
Unable to convert a string to an integer. Getting Error:
ValueError: invalid literal for int() with base 10: '2674'
I have read many answers and most of them the reason for not working is because it is a float and people use int(), but here clearly it is an integer.
like1 = '2,674 likes'
number = int(like1.split()[0])
print('This is the numer ::',number)
I expect the code to run without an error and print out the number. My actual implementation is to compare it with an integer. For eg. number > 1000, but that throws up the error that you can't compare a string and int, therefore I wanted to modify it into an int. I did not want to post that code since it was pretty big and messy.
Please ask for clarifications, if I have missed any required details!
Your problem is the comma in 2,674. Some locations use that as a decimal point, but your location does not, and you want it to separate groups of three digits in an integer. Python does not use it in that way.
So either remove the comma or change it to an underscore, _, which recent versions of Python allow in an integer. Since I do not know your version of Python I recommend removing the comma. Use this:
number = int(like1.split()[0].replace(',', ''))
By the way, the error message you show at the top of your question is not the actual error message. The actual message shows the comma in the string:
ValueError: invalid literal for int() with base 10: '2,674'
If you continue asking questions on this site, be sure to show the actual errors. In fact, you should copy and paste the entire traceback, not just the final line. That will help us to correctly understand your problem and help you.
I am learning python.
I would like to arrange the literal lines for easy code reading and easy outputs reading.
Please see the following code for detail.
failed=True
if failed:
print('\
Failed.\n\
reason:...\n\')
Output
Failed.
reason:...
To arrange the outputs, that is, without no white spaces at the head of lines, literal lines in python code start at the head of lines. However it breaks python code indentation.
Do I have a way to arrange multiple literal lines for displaying without breaking python code indentation?
Thank you very much.
It's not pretty, but you can take advantage of the compiler's nature to concatenate adjacent string literals:
print('foo\n'
'bar\n'
'baz quux')
in python to have multi-line string you can use triple quotes:
failed=True
if failed:
print('''\
Failed.\n\
reason:...\n''')
This will break output indentation:
Failed.
reason:...
To keep output indentation and code indentation you should append text lines:
failed=True
if failed:
print("Failed.\nreason:...\n")
or:
print("Failed.\n" +
"reason:...\n")
or:
print("Failed.\n"
"reason:...\n")
output:
Failed.
reason:...
Another option is using textwrap.dedent together with a triple-quoted string literal. This allows you to freely keep typing your string at whatever indentation level you like and then just close it at the end, which can be easier for a long message:
import textwrap
failed=True
if failed:
print(textwrap.dedent("""\
Failed.
reason:...
you
entered
an
invalid
number"""))
which outputs, with no indentation:
Failed.
reason:...
you
entered
an
invalid
number
I think this syntax is pretty clean, leaving the overhead entirely to either side of your string, and allowing you to visually maintain the strict indentation.
yes use triple single quotes '''some text''' or double quotes """some text""".
Here is an example
failed=True
if failed:
print('''\
Failed.\n\
reason:...\n\n''')
I'm using Python 2.7.
I want to print a binary in decimal, but I'm receiving an error, which I do not understand.
Eg. I am trying:
print 0b111
I am expecting 7. But it returns:
Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.
Error: no "print" mailcap rules found for type "text/x-python"
Can you help? Just a beginner with Python!
... at /usr/bin/print ...
Sounds like you're invoking the script incorrectly. Either use a shebang that points to a Python executable or explicitly pass it to the executable.
python somescript.py
Im using the terminal on my mac to run some python and when i try to print a string i get an invalid syntax error.
Michaels-MBP:~ mike$ python text.py
File "text.py", line 2
print(‘hi’)
^
SyntaxError: invalid syntax
I've tried it with single quotes and with and without parentheses but i keep getting that error, what is wrong.
Should be:
print('hi')
You have proper British quotes ‘foo’. Those are the right symbols to use when writing human-readable texts, but Python wants actual single quotes '.
Your editor probably has some kind of smart-quotes feature enabled, it is wise to turn this off when writing code (e.g. configure your editor to detect extensions like .py).