>>> str(42)
'42'
>>> int('42')
42
Links to the documentation:
int()str()
str(x) converts any object x to a string by calling x.__str__(), or repr(x) if x doesn't have a __str__() method.
Convert integer to string in Python - Stack Overflow
Converting a string input to a number or integer
python - How do I parse a string to a float or int? - Stack Overflow
Python: Replace Numeric Value With String - Stack Overflow
Hello Everyone,
I was wondering if it's possible to get the input of a string from the user and convert it into an integer later on. I'm asking this as the code I'm working on requires a string input from the user of what service they'd like. I later had to add up the totals of the services and wondered if once the choice was selected or inputted then if it would become a number that later adds up to the total cost if multiple services are inputted.
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Python2 method to check if a string is a float:
def is_float(value):
if value is None:
return False
try:
float(value)
return True
except:
return False
For the Python3 version of is_float see: Checking if a string can be converted to float in Python
A longer and more accurate name for this function could be: is_convertible_to_float(value)
What is, and is not a float in Python may surprise you:
The below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: (float("1_3.4") == float(13.4)) is True
val is_float(val) Note
-------------------- ---------- --------------------------------
"" False Blank string
"127" True Passed string
True True Pure sweet Truth
"True" False Vile contemptible lie
False True So false it becomes true
"123.456" True Decimal
" -127 " True Spaces trimmed
"\t\n12\r\n" True whitespace ignored
"NaN" True Not a number
"NaNanananaBATMAN" False I am Batman
"-iNF" True Negative infinity
"123.E4" True Exponential notation
".1" True mantissa only
"1_2_3.4" False Underscores not allowed
"12 34" False Spaces not allowed on interior
"1,234" False Commas gtfo
u'\x30' True Unicode is fine.
"NULL" False Null is not special
0x3fade True Hexadecimal
"6e7777777777777" True Shrunk to infinity
"1.797693e+308" True This is max value
"infinity" True Same as inf
"infinityandBEYOND" False Extra characters wreck it
"12.34.56" False Only one dot allowed
u'ๅ' False Japanese '4' is not a float.
"#56" False Pound sign
"56%" False Percent of what?
"0E0" True Exponential, move dot 0 places
0**0 True 0___0 Exponentiation
"-5e-5" True Raise to a negative number
"+1e1" True Plus is OK with exponent
"+1e1^5" False Fancy exponent not interpreted
"+1e1.3" False No decimals in exponent
"-+1" False Make up your mind
"(1)" False Parenthesis is bad
You think you know what numbers are? You are not so good as you think! Not big surprise.
Don't use this code on life-critical software!
Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.
Try
def main() :
number = int(input("Enter your number: "))
base = int(input("Convert to\n" \
" Binary[2] - Octal[8] - Hexadecimal[16]: "))
base_string = "None"
if base == 2 :
base_string = "binary"
elif base == 8 :
base_string = "octal"
else:
base_string = "hexadecimal"
print("\n {} in {} is: {}".format(str(number), base_string, str(convert(number, 10, base))))
def convert(fromNum, fromBase, toBase) :
toNum = 0
power = 0
while fromNum > 0 :
toNum += fromBase ** power * (fromNum % toBase)
fromNum //= toBase
power += 1
return toNum
main()
Your issue was the "binary" part in the if-statement. It has virtually no effect neither on your code nor on your output. You have to store the literal representation ("binary",...) in some variable ("base_string"). Then you can use this variable in your output.
As an aside, it looks like your base conversion won't actually do what you want. You should look at How to convert an integer in any base to a string? to do the conversion properly (hexadecimal has letters A-F in it, those aren't handled by your code, for example).
To accept a name instead of a number, you need to change this line of code:
base = int(input("Convert to\n Binary[2] - Octal[8] - Hexadecimal[16]: "))
What's happening here? input() takes a line from stdin. In the interactive case, this means the user types something (hopefully a number) and then hits enter. We get that string. Then int converts that string to a number.
Your convert expects base to be a number. You want inputs like "binary" to correspond to base = 2. One way to achieve this is with a dict. It can map strings to numbers:
base_name_to_base = {'binary': 2, 'octal': 8, 'hexadecimal': 16}
base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]
Note that base_name_to_base[x] can fail (raise KeyError) if x is not a key in the dict. So you want to handle this (what if the user enters "blah"?):
while True:
try:
base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]
break
except KeyError:
pass
This will loop until we hit the break (which only happens when indexing into base_name_to_base doesn't raise the key error.
Additionally, you may want to handle different cases (ex. "BINARY") or arbitrary whitespace (ex. " binary "). You can do this by calling .lower() and .strip() on the string returned by input().