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
Related
I want to generate a random int and then use time.sleep().
I want it to generate something like 0.123 randomly.
Here is my code:
s = f"0.{str(random.randint(111, 333))}"
s = int(s)
time.sleep(s)
I am getting the error:
time.sleep(s)
ValueError: invalid literal for int() with base 10: '0.198'
I tried a lot of things, different ways of formatting it etc. No luck
You're trying to convert a floating point number (0.xxx) to an int.
What you need to do is convert it to a float instead:
s = float(s)
Is there any possible direct way to convert 345., which is actually a str type, to int type?
I tried int('345.') but it gives:
ValueError: invalid literal for int() with base 10: '345.'
Probably not very elegant, but does what you want without modifying your string:
int(float('345.'))
Ugly solution, but works :)
int('365.'.split('.')[0])
I think it is understandable first delete the last char then convert it to float.
fl = "345."
fl = fl[:-1]
fl = float(fl)
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 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.