字元串 字元串或串(String)是由數字、字母、下劃線組成的一串字元,用雙引號或單引號包裹的為字元串 下麵示例: 語法錯誤 第一行出現三個單引號,Python 解析器匹配不上成對的引號,所以報錯。 解決方法:1、可使用雙引號包裹 2、可以使用反斜杠\ 轉義字元 字元串 、數字互轉 內置函數int( ...
字元串
字元串或串(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:\news
3 >>> print r"c:\news"
4 c:\news
5 >>> 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 14
11 >>> str("8")+ "6"
12 '86'