str与repr,input与raw_input比较

来源:互联网 发布:mac队装备 编辑:程序博客网 时间:2024/06/08 02:11

一.str与repr比较:

1.共同点:str和repr都是一个函数。

2.不同点:str:此函数将把参数值转换成合理形式的字符串;

                   repr:此函数则会创建一个字符串,然后以合法的python表达式形式来表示值;

3.实例str:

>>> print str("hello world")        

hello world
>>> print str(1000L)                 #将long参数转换成字符串

1000

4.实例repr:

>>> print repr("hello world")       
'hello world'
>>> print repr(1000L)              #重新创建一个字符串,以合法的python表达式输出 
1000L

>>> temp =42L
>>> print "the temperature is " +repr(temp)
the temperature is 42L

二.input与raw_input比较:

1.input函数:需要以合法的python表达式形式输入

如:

>>> name = input ("what is your name ?")
what is your name ?

当输入为数值型:3时,通过;当输入为字符型:lucy时,抱错:

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    name = input ("what is your name ?")
  File "<string>", line 1, in <module>
NameError: name 'lucy' is not defined

因为字符型的合法表达式应为:'lucy',如果输入'lucy'或者"lucy"则通过

2.raw_input函数:将会把所有的输入当原始数据处理

如:

>>> name = raw_input ("what is your name ?")
what is your name ?lucy
>>>

此时直接输入lucy就不会抱错。