I want to use format specifier on numbers in string
Alist = ["1,25,56.7890,7.8"]
tokens = Alist[0].split(',')
for number in tokens:
print "%6.2f" %number ,
Outcome: It gives me error.
TypeError: float argument required, not str
Your error clearly states that you are trying to pass a String off as a Float.
You must cast your string value to a float:
for number in tokens:
print '{:6.2f}'.format(float(number))
Note If you are using a version of python earlier than 2.6 you cannot use format()
You will have to use the following:
print '%6.2f' % (float(number),) # This is ugly.
Here is some documentation on Python 2.7 format examples.
Related
I have an ID DIS002789.I want to extract 2789 from the given ID.I have to use the extracted number in a for loop using a variable.
I tried using re.findall.
inputk='DIS0002789'
non_decimal = re.findall(r'[\d.]+', inputk)
for n in range(non_decimal, non_decimal + 1000):
Im getting 002789. But I want my output to be 2789.And also i cant use the for loop because of this.It shows a n error saying 002789 is an invalid syntax.
I tried converting it to int. but its shows the following error,
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
you can pass the result of re.findall(r'[\d.]+', inputk) to int in order to make it an integer. int('0123') will ignore leading zeroes.
Example:
inputk='DIS0002789'
non_decimal = int(re.findall(r'[\d.]+', inputk))
if you want it to be a string you can pass it to str again: str(int('0123')) == '123'
If you want the int value, you should convert it to integer as other answers show. If you only want the string, you can try adding the optional leading zeros:
inputk='DIS0002789'
non_decimal = re.findall(r':?[0]*(\d+)', inputk)
non_decimal
output:
['2789']
you can ignore leading zeros and convert it to an integer to use in a loop
inputk='DIS0002789'
non_decimal = int(re.findall(r':?[0]*(\d+)', inputk)[0])
how convert float to int to string?
with open(DATA_DIR+'/test.csv', 'r') as inp:
reader = csv.DictReader(inp, delimiter=',',fieldnames = ['Id', 'Target'])
for row in csv.reader(inp):
text_file.write("Text "+str(int(row[1])))
Error: ValueError: invalid literal for int() with base 10: '323.0'
EDIT: The CSV parser is already reading the data that you are trying to convert as a string. That string has decimal point values which it won't convert to int. It will convert it to float though.
Here are 2 ways to do this:
Just split the string and use the integral part
in your example do text_file.write('Text {:.0f}'.format(float(row[1]))
With the 2nd approach you are basically converting it to float and thereafter you don't care for anything on the right of the decimal. So .0f indicates you don't want anything after the decimal including the .. More on this formatting can be learned in the link I pasted below.
As you dig deeper you should continue to use type() to identify the incoming data before you decide what to do with it.
ORIGINAL PART:
You don't have to convert the data to achieve what you want. At the end of it you want to write to a file as a string. If what you are getting from the csv is a float then you could simply format your string as
write_line = 'Text {:06.2f}'.format(row[1])
text_file.write(write_line)
Of course you could condense the two lines.
There is more info in python's docs - https://docs.python.org/3/tutorial/inputoutput.html
x=Decimal(row[1]).normalize()
text_file.write(x)
Probably looks like row[1] is not having any numeric value. Can u specify what exactly it will hold?
Try printing row[i] before executing the int() function and see what value it is holding.
I have the following python code, which converts a binary string into plain-text:
import bin ascii
n = int('01100001011000100110001101100100', 2)
binascii.unhexlify('%x' % n)
This code functions properly, but I don't understand what's going on here.
What is the purpose of the "2" at the end of the int declaration?
What is the purpose of the "'%x' % n" argument?
What is the purpose of the 2 at the end of the int declaration?
According to the documentation, int can take a second argument: the base of the first argument.
What is the purpose of the '%x' % n argument?
%x in a string indicates that an item will be formatted to hexadecimal with lowercase letters. '%x' % n. It is similar to the builtin hex function, except it doesn't have the leading 0x in the string. An equivalent expression would be format(n, 'x').
perl hex() analog in python how to?
I have next perl code:
my $Lon = substr($Hexline,16,8);
say $output_f "Lon: " . hex($Lon) . "";
where $Hexline has "6a48f82d8e828ce82b82..." format
I try it on python
Lon = int(Hexline[16:24], 16)
f.write('lon = %s' % str(Lon)+'\n')
is it right?
EDIT: in perl's case hex() gives me a decimal value.
Yes, to convert an hexadecimal string to an integer you use int(hex_str, 16).
Note that in your write method call:
You don't need to concatenate two strings to add the new line character, you can add it to the formatting string directly.
To print integer you should use %d instead of %s.
You don't really need to call str to transform the integer into a string.
Hence, the write call could be written as:
f.write('lon = %d\n' % Lon)
Alternatively, you could also use format this way:
f.write('lon = {0}\n'.format(Lon))
When trying to convert a string into integer to be used as a variable later in the code, I get the following:
print int(urlsuccessful[i])
ValueError: invalid literal for int() with base 10: '2,919,247'
locale.atoi() will "demark" integers based on the current locale setting.
If only problems are commas, try:
>>> int("2,919,247".replace(",", ""))
2919247
int does not understand commas, you'll want to remove those before trying to convert
You can just do
def int2str(my_integer):
return "%d" % my_integer