Python 學習筆記(七)Python字串(一)

來源:互聯網
上載者:User

標籤:轉義符   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字串(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.