Convert integer to string in Python - python

How do I convert an integer to a string?
42 ⟶ "42"
For the reverse, see How do I parse a string to a float or int?. Floats can be handled similarly, but handling the decimal points can be tricky because floating-point values are not precise. See Converting a float to a string without rounding it for more specific advice.

>>> 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.

Try this:
str(i)

There is no typecast and no type coercion in Python. You have to convert your variable in an explicit way.
To convert an object into a string you use the str() function. It works with any object that has a method called __str__() defined. In fact
str(a)
is equivalent to
a.__str__()
The same if you want to convert something to int, float, etc.

To manage non-integer inputs:
number = raw_input()
try:
value = int(number)
except ValueError:
value = 0

>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5

For Python 3.6, you can use the f-strings new feature to convert to string and it's faster compared to str() function. It is used like this:
age = 45
strAge = f'{age}'
Python provides the str() function for that reason.
digit = 10
print(type(digit)) # Will show <class 'int'>
convertedDigit = str(digit)
print(type(convertedDigit)) # Will show <class 'str'>
For a more detailed answer, you can check this article: Converting Python Int to String and Python String to Int

In Python => 3.6 you can use f formatting:
>>> int_value = 10
>>> f'{int_value}'
'10'
>>>

The most decent way in my opinion is ``.
i = 32 --> `i` == '32'

You can use %s or .format:
>>> "%s" % 10
'10'
>>>
Or:
>>> '{}'.format(10)
'10'
>>>

For someone who wants to convert int to string in specific digits, the below method is recommended.
month = "{0:04d}".format(localtime[1])
For more details, you can refer to Stack Overflow question Display number with leading zeros.

With the introduction of f-strings in Python 3.6, this will also work:
f'{10}' == '10'
It is actually faster than calling str(), at the cost of readability.
In fact, it's faster than %x string formatting and .format()!

There are several ways to convert an integer to string in python.
You can use [ str(integer here) ] function, the f-string [ f'{integer here}'], the .format()function [ '{}'.format(integer here) and even the '%s'% keyword [ '%s'% integer here]. All this method can convert an integer to string.
See below example
#Examples of converting an intger to string
#Using the str() function
number = 1
convert_to_string = str(number)
print(type(convert_to_string)) # output (<class 'str'>)
#Using the f-string
number = 1
convert_to_string = f'{number}'
print(type(convert_to_string)) # output (<class 'str'>)
#Using the {}'.format() function
number = 1
convert_to_string = '{}'.format(number)
print(type(convert_to_string)) # output (<class 'str'>)
#Using the '% s '% keyword
number = 1
convert_to_string = '% s '% number
print(type(convert_to_string)) # output (<class 'str'>)

Here is a simpler solution:
one = "1"
print(int(one))
Output console
>>> 1
In the above program, int() is used to convert the string representation of an integer.
Note: A variable in the format of string can be converted into an integer only if the variable is completely composed of numbers.
In the same way, str() is used to convert an integer to string.
number = 123567
a = []
a.append(str(number))
print(a)
I used a list to print the output to highlight that variable (a) is a string.
Output console
>>> ["123567"]
But to understand the difference how a list stores a string and integer, view the below code first and then the output.
Code
a = "This is a string and next is an integer"
listone=[a, 23]
print(listone)
Output console
>>> ["This is a string and next is an integer", 23]

You can also call format():
format(42) # 42 --> '42'
If you want to add a thousands separator:
num = 123456789
format(num, ",") # '123,456,789'
f"{num:,}"
"{:,}".format(num)
or to convert to string representation of floats
format(num, ",.2f") # '123,456,789.00'
f"{num:,.2f}"
'{:,.2f}'.format(num)
For a "European" separator:
format(num, "_.2f").replace('.', ',').replace('_', '.') # '123.456.789,00'
f"{num:_.2f}".replace('.', ',').replace('_', '.')
"{:_.2f}".format(num).replace('.', ',').replace('_', '.')

Related

How to read inputs separated by spaces in python, as different data types dynamically preferably onto a List?

Is there a way to insert first input as str the next input as int and the next as float onto a list. Assuming the three inputs are separated by spaces are taken as input.
data = map(str,int,float,input.split()) # Something like this, I know the syntax here is wrong
You can do it simply:
task = input().split()
task[1] = int(task[1])
task[2] = float(task[2])
or in a more convoluted way:
task = [ f(x) for (f, x) in zip([str, int, float], input().split()) ]
Yup, you can do this. Try this:
>>> task = input().split()
hello 3 42.3
>>> task # task is a list of strings
['hello', '3', '42.3']
# get the 3 parts of task
>>> string = task[0]
>>> int = int(task[1])
>>> float = float(task[2])
>>> string, int, float
('hello', 3, 42.3)
There isn't some already available way to do it but you can write your own function for it; such as this:
def my_input(data_types):
user_input = input()
split_user_input = user_input.split()
converted_input_tokens = []
for input_token, data_type in zip(split_user_input, data_types):
converted_input_tokens.append(data_type(input_token))
return converted_input_tokens
It will do exactly(no more, no less) what you showed in the example you gave. You can use it this way:
>>> my_input((str, int, float))
1 2 3
Which will return:
['1', 2, 3.0]
It can be made much more generic, of course. For example, you could add arguments for the input prompt, the sep and maxsplit for the str.split method used in the function, etc.
If you are in doubt about how to do that, have a look at the official documentation for input, str.split and also do some research on type-conversions in Python.
you can explicitly define each input as particular type.

why formatted strings do not need to have type conversion before including the variable or operation in the {curly brackets}?

as you know , python is a strongly typed language that does not allow concatenation of type int with str.
As you can see below; As I stated above python does not allow for such operations(concatenation of str with int due to the language's features).
a = 10
b = '20'
print(a + b)
#throws the error **TypeError: unsupported operand type(s) for +: 'int' and 'str'**
But Look into this too:
a = 1
b = '2'
print(f"{a} and {b}")
print("{} and {}".format(a, b))#or this for example
Here I did not converted variable a which has an int type assigned to ; into string, but I can include it in the formatted string
My question is ... what happens under the curtains when python interpreter encounters with this expression print(f"{a} and {b}")
what happens under the curtains when python interpreter encounters with this expression print(f"{a} and {b}")
What happens is that before a and b are built into the string, str(a) and str(b) are called. You can see this yourself when you build 2 classes like this:
class Test1(object):
pass
class Test2(object):
def __str__(self):
return "surprise"
which do the same (nothing) but Test2 returns "surprise" when str(Test2()) is called.
When you want to convince yourself try this:
t1 = Test1()
t2 = Test2()
print(t1)
print(t2)
print(f"{t1}")
print(f"{t2}")
print("{}".format(t1))
print("{}".format(t2))
Each time the same two lines are printed.
This is documented in chapter 2 of Python's documentation:
If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls str() on the result, '!r' calls repr(), and '!a' calls ascii().
If no conversion is specified, it immediately continues to the following step:
The result is then formatted using the format() protocol. The format specifier is passed to the __format__() method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string.
The __format__() method then follows the format specifier mini-language syntax to determine the resulting string representation.
In your case the result is the same as calling str() on the variables, but this does not apply to all variables. Based on #Marv's answer, here is a little demonstration to show the difference:
class Test:
def __str__(self):
return "surprise"
def __format__(self, format_spec):
return "test"
t1 = Test()
print(t1)
print(str(t1))
print(f"{t1}")
print("{}".format(t1))
>>> surprise
>>> surprise
>>> test
>>> test

How do I check if an input is a string or int in Python 2.x?

I am trying to check if an input is a word or a number.
var = input("var: ")
if isinstance(var, str):
print "var = word"
else:
print "var = number"
This is the code I came up with but sadly doesn't work;
I'm new to python and programming in general so I don't know alot of commands,
any suggestion would be appreciated ^^
Did you try str.isdigit()?
For example:
v = raw_input("input: ")
if v.isdigit():
int(v)
print "int"
else:
print "string"
input() would always return for you a string (str type). there are several things you can do with that string to check if it's an int
you can try casting that string to an int:
var = input("var: ")
try:
var = int(var)
except ValueError:
print "var is a str"
print "var is an int"
you can use regular expression to check if the string contains only digits (if your int is decimal, for other bases you'd have to use the appropriate symbols):
import re
var = input("var: ")
if re.match(r'^\d+$', var):
print "var is an int"
else:
print "var is a str"
input() will take and evaluate your input before handing it over to you. That is, if the user enters exit(), your application will exit. This is undesirable from a standpoint of security. You would want to use raw_input() instead. In this case you can expect the returned value to be a string.
If you still want to check if the strings content is convertible to a (integer) number, please follow the approach discussed here:
How do I check if a string is a number (float) in Python?
A short outline: Just try to convert it to a number and see if it fails.
Example (untested):
value = raw_input()
try:
int(value)
print "it's an integer number"
except ValueError:
print "it's a string"
For reference:
https://docs.python.org/2/library/functions.html#int
https://docs.python.org/2/library/functions.html#input
https://docs.python.org/2/library/functions.html#raw_input
Note that the semantics of the input() function change with Python 3:
https://docs.python.org/3/library/functions.html#input
To check the variable type you can do the following:
>>> x = 10
>>> type(x)
<type 'int'>
For string:
>>> y = "hi"
>>> type(y)
<type 'str'>
Using isinstance:
x = raw_input("var: ")
try:
int(x)
except ValueError:
print "string"
else:
print "int"
As #paidhima said the input function will always return a string in python 3.x.
Example:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> var = input("var: ")
var: 12
>>> var
'12'
>>>type(var)
<class 'str'>
>>>
If i do the following:
>>> var = input("var: ")
var: aa
>>> var
'aa'
>>> type(var)
<class 'str'>
>>>
They are both string because it is not a good idea to have the program decide if it's gonna give us a string or and integer, we want the logic that we build in the program to handle that.
In python3.x you example is not gonna work, but you can try this this:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
var = input('var: ')
# we try to conver the string that we got
# in to an intiger
try:
# if we can convert it we store it in the same
# variable
var = int(var)
except ValueError:
# if we can't convert we will get 'ValueError'
# and we just pass it
pass
# now we can use your code
if isinstance(var, str):
print("var = word")
else:
print("var = number")
# notice the use of 'print()', in python3 the 'print is no longer
# a statement, it's a function
Now back to your script using python2.x.
As i said above it's not a good practice to use the function input, you can use raw_input that works the same in python2.x like input in python3.x .
I'm gonna say it again because i don't want to confuse you :
Python2.x:
input
# evaluates the expression(the input ) and returns what
# can make from it, if it can make an integer it will make one
# if not it will keep it as a string
raw_input
# it will always return the expression(the input ) as a string for
# security reasons and compatibility reasons
Python3.x
input
# it will always return the expression(the input ) as a string for
# security reasons and compatibility reasons
Attention, in python3.x there is no raw_input .
Your code should work just fine, in python2.x, make sure you use the right python, and i hope this helped you in a way or another.

convert string to int?

Working on a letter-guessing game.
Why is it that in the following example, when I hardcode the value of the variable, "userGuessPosition" to 2, the code works as expected.
secretWord = ('music')
userGuessPosition = 2
slice1 = (secretWord.__len__()) - userGuessPosition - 1
print (secretWord[slice1:userGuessPosition])
But when I rely on the input() function and type in 2 at the prompt, nothing happens?
secretWord = ('music')
userGuessPosition = 0
userGuessPosition == input()
slice1 = (secretWord.__len__()) - userGuessPosition - 1
print (secretWord[slice1:userGuessPosition])
I assume this is because my keyboard input of "2" is being seen as a string and not an integer. If this is the case, then I'm unclear on the proper syntax to convert it.
userGuessPosition = int(input())
(Single =; int converts a string to an int)
The problem is not that the input is recognized as a string, but rather in the syntax: you're doing a comparison operation where you should be doing an assignment operation.
You have to use
userGuessPosition = input()
instead of
userGuessPosition == input()
The input() function actually does convert the input number into the most appropriate type, sp that should not be an issue. If however you need to convert a string (say, my_string) to an integer, all you need to do is my_int = int(my_string).
EDIT
As mentioned below by #HenryKeiter, depending on your Python version, you may in fact need to convert the return value of input() to an integer by hand, since raw_input() (which always takes in the input as a string) was renamed to input() in Python 3.

variable number of digit in format string

Which is a clean way to write this formatting function:
def percent(value,digits=0):
return ('{0:.%d%%}' % digits).format(value)
>>> percent(0.1565)
'16%'
>>> percent(0.1565,2)
'15.65%'
the problem is formatting a number with a given number of digits, I don't like to use both '%' operator and format method.
I like this one:
'{0:.{1}%}'.format(value, digits)
Test:
>> '{0:.{1}%}'.format(0.1565, 0)
'16%'
>> '{0:.{1}%}'.format(0.1565, 2)
'15.65%'
* does what you want, for printf-style string formatting.
>>> def percent(value, digits=0):
... return '%.*f%%' % (digits, value * 100)
...
>>> percent(0.1565, 2)
'15.65%'
Advanced string formatting (defined in PEP 3101 and documented in 7.1.3. Format String Syntax) doesn't seem to be capable of doing this in one pass. (See 7.1.3.1. Format Specification Mini-Language: precision is integer only.)
From the docs:
Minimum field width (optional). If specified as an '*' (asterisk), the
actual width is read from the next element of the tuple in values, and
the object to convert comes after the minimum field width and optional
precision.
Example:
def percent(value, digits=0):
print '%.*f%%' % (digits, value*100)
>>> percent(0.1565, 2)
15.65%

Categories

Resources