字符串

  • 字符串符號
可使用單引號和雙引號
"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
相關文章
相關標籤/搜索