I have got the value from database 350,000,000.00 now I need to convert it to 350000000.
Please provide a solution on this using Python 3.6+ version
Thanks
Let the input be in a variable, say
a="350,000,000.00"
Since, the digits are comma , separated, that needs to be removed.
a.replace(",","")
>>> 350000000.00
The resultant string is a float. When we directly convert the string to integer, it will result in an error.
int(a.replace(",",""))
>>>Traceback (most recent call last):
File "python", line 2, in <module>
ValueError: invalid literal for int() with base 10: '350000000.00'
So, convert the number to float and then to int.
int(float(a.replace(",","")))
>>>350000000
Store the value in a variable and then parse it with int(variable_name)
eg. If you store the value in variable a, just write
int(float(a))
def convert(a):
r = 0
s = a.split(".")[0]
for c in s.split(","):
r = r * 1000 + int(c)
return r
s = convert("350,000,000.00")
Related
I have a csv file and I have to clean data.The problem is that I can fill the empty values by df.fillna() but there are some continious numbers in string which needs to be converted to float or int for further calculations.
I tried couple of methods but cannot find a solution.
Kindly help as I am new in data science field and maybe have made some mistake asking the question.
This column has an string value : df['hum'][316] = '64.70'
type(df['hum'][316]) = str
I stored the string value to a variable and then used float(value) but it gives an error.
value = df['hum'][316]
>>>' "64.70"'
type(value)
>>> str
float(value)
>>>ValueError: could not convert string to float: ' "64.70"'
ValueError: could not convert string to float: ' "64.70"'
df['hum'][316] = float(df['hum'][316])
seems the problems is the " inside the string, remove it by using a regular expression
import re
value = df['hum'][316]
value=re.sub('"','',value)
float(value)
instead of float possible to check also astype for cast operations applying on the whole df or series (column)
if you want to change the whole column of df to a float try:
df['hum'] = df['hum'].str.replace('"', '')
df['hum']=df['hum'].astype('float')
regards giulio
I am following a tutorial and I am getting an error.
My code should be this:
salaries = {'John':'20','Sally':'30','Sammy':'15'}
print(salaries['John'])
salaries['John'] = salaries['John'] + 30
print(salaries['John'])
I am getting back an error like this
Traceback (most recent call last): File "print.py", line 9, in
salaries['John'] = salaries['John'] + 30 TypeError: can only concatenate str (not "int") to str
Can you help me with this?
This should fix it:
salaries['John'] = str(int(salaries['John']) + 30)
You need to convert the salaries of John to an int add 30 and then convert it back to a string.
This will change salaries['John'] from 20 to 50
If you wanted to include the 30 you'd have to put something like str(30). That's why it's giving you that error cause 30 is an int and the rest are strings you can't combine strings and ints. Hope this helps
The "+" operator is using for concatenate strings, adding numbers, etc.
in your case you trying to add two integers but in your dictionary "salaries" the values are strings.
you can convert the value to int, adding the numbers and then convert to string to store the value.
Try this:
salaries['John'] = str(int(salaries['John']) + 30)
print(salaries['John'])
I'm having an issue getting from hexadecimal string to hexadecimal integer in Python 3.
When you write hex(12) you get the output 0xc which is a str class. However, when you type fx. int = 0x55 the class/type is an INTEGER.
How do you go from "0x55" to 0x55 (as an integer)
Thank you :)
You might be getting confused between the concepts of a number's representation and a number's value. For example, the following evaluates to True in Python: 83 == 0o123 == 0x53 The decimal representation is 83, and octal representation is 123, and the hexadecimal representation is 53. However, the value of all those representations are the same. For the sake of explanation, I will give you the value using the decimal representations; the value is 83.
If you are trying to convert a string into a number, you may want to look at the eval and ast.literal_eval functions. Here is a demonstration of how you might use the second:
>>> number = 12345
>>> hex_string = hex(number)
>>> oct_string = oct(number)
>>> print('hex_string =', repr(hex_string))
hex_string = '0x3039'
>>> print('oct_string =', repr(oct_string))
oct_string = '0o30071'
>>> number == ast.literal_eval(hex_string)
True
>>> number == ast.literal_eval(oct_string)
True
>>>
So, I want to write a program with python 3 where it can help users calculate the circumference of a circle and sphere. So far this is what I have.
pi = 3.14159
value = input("Enter the value of your radius:")
circ = 2*pi*value
print(circ)
But, it keeps saying "can't multiply sequence by non-int of type 'float'". How do I fix this? And, how do I make the input as numbers only? Thank you.
try
value = float(input("Enter the value of your radius: "))
Note that this will throw an error if the input isn't a number.
Also, while you cant control what they input, you could just keep asking for a number if they type anything else like this:
while True:
try:
value = float(input("Enter the value of your radius: "))
except ValueError:
print("Please enter a number")
Running your program as-is reports
bash-3.2$ python3 test.py
Enter the value of your radius:10
Traceback (most recent call last):
File "test.py", line 3, in <module>
circ = 2*pi*value
TypeError: can't multiply sequence by non-int of type 'float'
The problem is value contains a string after the input returns
and python is trying to multiply a float (2*pi) and the string (character sequence value).
To correct this you probably want to convert value to a float before the multiplication.
e.g.
pi = 3.14159
value = input("Enter the value of your radius:")
circ = 2*pi*float(value)
print(circ)
Sample run with this change
bash-3.2$ python3 test.py
Enter the value of your radius:10
62.8318
I have been practicing the basics now i am try to do a practice task in uni and i can't seem to find where i am going wrong can anyone point me in the right direction and explain to me what i am doing wrong please , thank you
this is the question
Write some Python code that requests 2 numbers and prints the result of applying the operators + - * / eg.
Please enter your first number:5
Please enter your second number:3
5 + 3 = 8
5 – 3 = 2
5 * 3 = 15
5 / 3 = 1.666666667
Test this code with at least ten different values. (Hint:You may need to think about how you manage the types)
and this is my coding
A= input ("Please enter your first number:")
B= input ("please enter your second number:")
A+B
A-B
A*B
A/B
and i get an error message saying
Please enter your first number:5
please enter your second number:3
Traceback (most recent call last):
File "/Users/salv/Documents/PRACTISE PYTHIN.py", line 6, in <module>
A-B
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>
Input will return a string object, and the - operator expects two integers. Cast it to an int with int()
i.e.
A = int(input("Please enter your first number:"))
This happens because when python reads some user input, it reads it as a string (of type str), not as a number (of type int in this case).
So what you need to do is to convert the string representation of the number you entered, into a numeric type. This can be done by calling int() on your string as follows:
users_input = input("Enter a number: ")
A = int(users_input)
Consider this:
>>> A = input("Enter a number: ")
Enter a number: 5
>>> A
'5'
Notice the quotes around 5. This indicates that it's a string. You could confirm this with the use of type
>>> type(A)
<class 'str'>
>>> B = int(A)
>>> B
5
Note: no quotes around 5. It's a numeric type. Since it isn't followed by a .0, it's not a float (floating point decimal type). Rather, it is an int (integer type). Again, this can be confirmed with type
>>> type(B)
<class 'int'>