字符串

  • 字符串符号
可使用单引号和双引号
"hello,word"
'hello,word'
'Let's go' #错误
'Let\'s go' #正确,使用 \ 进行转义

  • 字符串表示:str和repr
str类型,将值转换为字符串
repr()函数也是
>>> "hello""world"
'helloworld'
>>> print repr("Hello,Wrod")   #虽然str 和 repr 输出的都是字符串,可是貌似有些不同
'Hello,Wrod'
>>> print repr(1000L)
1000L                         #输出 1000L 更为合法的表示值
>>> print str("Hello,Word")
Hello,Word
>>> print str (1000L)
1000                          #输出 1000  更易阅读的表达式
案例
>>> print "The temperature is" +temp

#报错了,由于string类型没法与int类型相加,经过 str或者repr()函数转化
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    print "The temperature is" +temp
TypeError: cannot concatenate 'str' and 'int' objects
    
>>> print "The temperature is" + str(temp)
The temperature is 42
>>> print "The temperature is" + " " +repr(temp)
The temperature is 42
相关文章
相关标签/搜索