python整型、浮点型分别与字符串互转

1、str()将整型、浮点型转换成字符串

>>> num = 999
	  
>>> s = str(num)
	  
>>> type(s)
	  

>>> s
	  
'999'
>>> 
>>> n = 999.888
	  
>>> s = str(n)
	  
>>> type(s)
	  

>>> s
	  
'999.888'
>>> 

2、int()将符合整型规范的字符串转换成整型

>>> s1 = '999'
	  
>>> if s1.isdigit():
	  num1 = int(s1)

	  
>>> type(num1)
	  

>>> num1
	  
999

3、float()将符合浮点型规范的字符串转换成浮点型

>>> s2 = '999.888'
	  
>>> if s2.isdigit():
	  num2 = float(s2)

	  
>>> type(num2)
	  
Traceback (most recent call last):
  File "", line 1, in 
    type(num2)
NameError: name 'num2' is not defined
>>> 
	  
>>> s2.isdigit()
	  
False
>>> s2 = '999.888'
	  
>>> num2 = float(s2)
	  
>>> type(num2)
	  

>>> num2
	  
999.888
>>> 

 

你可能感兴趣的:(Python)