How to format a string with a width and a literal? - python

I have Python (2.7) code which takes a float, formats it with thousand-separating commas and 3 decimal places, and adds the string literal " sec" afterwards.
The result is then formatted further by being aligned left and given a width of 20:
num = '{:,.3f} sec'.format(1200300.4443333333)
print '{:<20}'.format(num) + 'more'
Ouput:
1,200,300.444 sec more
I wanted to condense this into a single format call, but I couldn't figure out how to use the width properly with the string literal.
I tried the following:
num = '{:,.3f}'.format(1200300.4443333333)
print '{:<20} sec'.format(num) + 'more'
But the output isn't the same:
1,200,300.444 secmore
I also tried the following:
num = '{:,.3f}'.format(1200300.4443333333)
print '{:<20 sec}'.format(num) + 'more'
But that failed:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print '{:<20 sec}'.format(num) + 'more'
ValueError: Invalid conversion specification
Is there any way to condense the initial code into a single format call?

Not sure if it is but the following code might be what you're after:
num = '{:<20,.3f} sec more'.format(1200300.4443333333)
print(num)
# 1,200,300.444 sec more

Related

callig str when using functions

im writing some code to print a triangle with so many rows but when i try it it says,
how many rows in the triangle 5
Traceback (most recent call last):
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 6, in <module>
triangle(5)
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 5, in triangle
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
TypeError: 'str' object is not callable
anybodyknow whats going on here
the code i am using is
inttrow=int(input("how many rows in the triangle "))
def triangle(row):
for i in range(1,row):
x=int(inttrow)-int(i)
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
triangle(5)
The problem is the punctuation in your print statement. You're printing three strings in succession, but you forgot to put any concatenation operation between them. Try this:
print ((x*(str(" "))) + (int(i)*(str("*"))) + ((int(row)-int(i))*(str(" "))))
Further, why are you doing all these type coercions -- all of those variables already have the proper types. Cut it down to this:
print (x*" " + i*"*" + (row-i)*" ")
You are trying to contatenate strings by placing them near each other in the code like this:
("hello")(" ")("world")
Try that on the command line and see what happens. It is not the syntax of the language you are using. Then try using the plus sign.
"hello" + " " + "world"

Why am I receiving this error when sorting a Text file by a certain column based upon number?

My code for the sorting of the file.
g = open('Lapse File.txt', 'r')
column = []
i = 1
next(g)
for line in g:
column.append(int(line.split('\t')[2]))
column.sort()
This is the error I get.
Traceback (most recent call last):
File "E:/Owles/new lapse .py", line 51, in <module>
column.append(int(line.split('\t')[2]))
ValueError: invalid literal for int() with base 10: '-8.3\n
My main question is why is there a \n. Earlier in the code I had written to another text file and wrote it by column from a previously read in file.
This is my code for writing the file
for columns in (raw.strip().split() for raw in Sounding):
if (i >2 and i <=33):
G.write(columns [3]+'\t'+columns[2]+'\t'+columns[4]+'\n')
i = i + 1
elif (i >= 34):
G.write(columns [0]+'\t'+columns[1]+'\t'+columns[2]+'\n')
i = i + 1
else:
i = i + 1
I am unsure if writing the lines like that is the issue because I have inserted the new line function.
The traceback is telling you exactly what happened:
ValueError: invalid literal for int() with base 10: '-8.3\n'
The problem here is that, while int() can handle the negative sign and the trailing newline character, it can't handle the decimal point, '.'. As you know, -8.3 may be a real, rational number, but it's not an integer. If you want to preserve the fractional value to end up with -8.3, use float() instead of int(). If you want to discard the fractional value to end up with -8, use float() to parse the string and then use int() on the result.
-8.3:
column.append(float(line.split('\t')[2]))
-8:
column.append(int(float(line.split('\t')[2])))
Because only numeric strings can be cast to integers; look at this:
numeric_string = "109"
not_numeric_string = "f9"
This is okay:
>>> int(numeric_string)
109
And it cannot be cast:
>>> int(not_numeric_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'f9'
So somewhere in your script it is getting a non-numeric string.
It seems as though the "-8.3\n" string sequence has raised the error, so you must strip escape chars as well.

Python formatting Error (unsupported) [duplicate]

This question already has answers here:
Python: ValueError: unsupported format character ''' (0x27) at index 1
(5 answers)
Closed 8 years ago.
I am building a string with this method.
But for some reason I am getting the following error
ValueError: unsupported format character ''' (0x27) at index 38
I have no idea where this is coming from. I checked for typos but nothing.
s = "SELECT %s FROM %s "
data = [colName, tableName]
if whereRoughly:
s+= "(WHERE "
for i in range(len(whereRoughly[0])):
s += "%s LIKE '%%s%' "
if i+1 < len(whereRoughly[0]): s += "OR "
data.append(whereRoughly[0][i])
data.append(whereRoughly[1])
s+= ")"
s += "ORDER BY %s;"
data.append("desc")
print s
print data
print s % tuple(data)
Here I call all the upper code
s.makeSelect(tableName="students", whereRoughly=([1,2], "Wes"))
This is the actual output
SELECT %s FROM %s (WHERE %s LIKE '%%s%' OR %s LIKE '%%s%' )ORDER BY %s;
['*', 'students', 1, 'Wes', 2, 'Wes', 'desc']
The problem is here:
"'%%s%'"
There's no format code %', and trying to use it causes an error.
>>> "'%%s%'" % "foo"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unsupported format character ''' (0x27) at index 5
I assume that you're trying to get the SQL LIKE syntax like '%foo%' (enclosed on either side by % and a single quote.
To get that formatting using the old-style % formatting in Python, you need to escape the leading and trailing percents like this:
>>> "'%%%s%%'" % "foo"
"'%foo%'"
(See the docs.)
This is cleaner with modern-style string.format:
>>> "'%{0}%'".format('foo')
"'%foo%'"
(also, the comment above about not using += to build strings is a valid one -- prefer format and join).

python convert string "0" to float gives error

i have the following code in my python script, to launch an application and grab the output of it.
An example of this output would be 'confirmed : 0'
Now i only want to know the number, in this case zero, but normally this number is float, like 0.005464
When i run this code it tells me it cannot convert "0" to float. What am i doing wrong?
This is the error i get now:
ValueError: could not convert string to float: "0"
cmd = subprocess.Popen('/Applications/Electrum.app/Contents/MacOS/Electrum getbalance', shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
if "confirmed" in line:
a,b=line.split(': ',1)
if float(b)>0:
print "Positive amount"
else:
print "Empty"
According to the exception you got, the value contained in b is not 0, but "0" (including the quotes), and therefore cannot be converted to a float directly. You'll need to remove the quotes first, e.g. with float(b.strip('"')).
As can be seen in the following examples, the exception description does not add the quotes, so they must have been part of the original string:
>>> float('"0"')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: "0"
>>> float('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: a
I have tested the code and found that split(': ', 1) result contains string
>>> line = "1: 456: confirmed"
>>> "confirmed" in line
True
>>> a,b=line.split(': ', 1)
>>> a
'1'
>>> b
'456: confirmed'

How to convert str to int and add them together?

I've spent the last 2 hours trying to find a solution for this and came up with nothing. So either this is not possible or its so basic that no one write about this. Basically I have 2 strings that both equal numbers, but when I go to add them together I get a concatenate instead of a number.. here is my code (Python)
currentNukeScriptName = nuke.root().name()
splitUpScriptName1 = currentNukeScriptName.split('/')
splitUpScriptName2 = splitUpScriptName1[-1]
splitScriptNameAndExtention = splitUpScriptName2.split('.')
currentNukeScriptName = splitScriptNameAndExtention[0]
splitUpCurrentScriptName = currentNukeScriptName.split('_')
currentVersionNumber = splitUpCurrentScriptName[-1]
decimalVersionNumber = "1" + "," + str(currentVersionNumber)
addingNumber = 1
newVersionNumber = str(decimalVersionNumber) + str(addingNumber)
print newVersionNumber
decimaleVersionNumber = 1,019
If I change the newVersionNumber code too:
newVersionNumber = int(decimalVersionNumber) + int(addingNumber)
I get:
# Result: Traceback (most recent call last):
File "<string>", line 10, in <module>
ValueError: invalid literal for int() with base 10: '1,019'
I am unsure what to do.. Is this not possible? Or am I doing something totally wrong?
Edit:
So the problem was found in the decimalVersionNumber where I was adding a comma. What would be the best way of keeping the comma and still adding the numbers together?
ValueError: invalid literal for int() with base 10: '1,019'
Sounds like it doesn't like the comma - try removing it first.
You need to use
int.Parse(decimalVersionNumber) + int.Parse(addingNumber)
This will parse the string representation of the numbers into integers, so they can be added.
eg:
String concatenation:
"10" + "20" = "1020"
Integer addition, parsed from strings:
int.Parse("10") + int.Parse("20") = 30

Categories