標籤:轉義符 ali 文法 syn ring and str erro 數字
字串
字串或串(String)是由數字、字母、底線組成的一串字元,用雙引號或單引號包裹的為字串
1 >>> "hello world"2 ‘hello world‘3 >>> ‘hello world‘4 ‘hello world‘5 >>> "250"6 ‘250‘7 >>> type("200")8 <type ‘str‘>
下面樣本:
語法錯誤 第一行出現三個單引號,Python 解析器匹配不上成對的引號,所以報錯。
解決方案:1、可使用雙引號包裹 2、可以使用反斜線\ 逸出字元
1 >>> ‘What‘s your name?‘ 2 File "<stdin>", line 1 3 ‘What‘s your name?‘ 4 ^ 5 SyntaxError: invalid syntax 6 >>> "What‘s your name?" 7 "What‘s your name?" 8 >>> ‘What\‘s your name?‘ 9 "What‘s your name?"10 >>>
字串 、數字互轉
內建函數int() str() float()
1 >>> a = int("200") 2 >>> a 3 200 4 >>> type(a) 5 <type ‘int‘> 6 >>> b = str(200) 7 >>> type(b) 8 <type ‘str‘> 9 >>> c = float("200.5")10 >>> type(c)11 <type ‘float‘>12 >>>
轉義符
第5行出現 \n 換行
解決方案:使用反斜線\ 或者在原始字串前+r ,會顯示原始字串
1 >>> print "c:\\news"2 c:\news3 >>> print r"c:\news"4 c:\news5 >>> print "c:\news"6 c:7 ews
字串相加
字串相加是將兩個字串拼接在一起
1 >>> "3" + "6" 2 ‘36‘ 3 >>> "py" + "thon" 4 ‘python‘ 5 >>> 8 + "6" 6 Traceback (most recent call last): 7 File "<stdin>", line 1, in <module> 8 TypeError: unsupported operand type(s) for +: ‘int‘ and ‘str‘ 不支援 int 和字串相加,我們可以將其轉換 9 >>> 8 + int("6")10 1411 >>> str("8")+ "6"12 ‘86‘
Python 學習筆記(七)Python字串(一)