Python - Append String and Number together

Introduction

Consider the following code:

# Python 3.X 
>>> "42" + 1 
TypeError: Can't convert 'int' object to str implicitly 

# Python 2.X 
>>> "42" + 1 
TypeError: cannot concatenate 'str' and 'int' objects 

+ can mean both addition and concatenation.

Convert to string or integer

Use conversion tools before you can treat a string like a number, or vice versa. For instance:

int("42"), str(42)          # Convert from/to string 
(42, '42') 
repr(42)                    # Convert to as-code string 
'42' 

The int function converts a string to a number.

The str function converts a number to its string representation.

You can't mix strings and number types around operators such as +, you can manually convert operands before that operation if needed:

S = "42" 
I = 1 
>>> S + I 
TypeError: Can't convert 'int' object to str implicitly 

Demo

S = "42" 
I = 1 # w  ww.  jav a 2 s  .  co m

print( int(S) + I )           # Force addition 
print(S + str(I) )           # Force concatenation

Result

You can convert floating-point-number to and from strings:

Demo

print( str(3.1415), float("1.5") )
text = "1.234E-10" 
print( float(text) )           # Shows more digits before 2.7 and 3.1
#   www .j av a2s  .  c  o  m

Result

Related Topic