Python入門(十四) 字串

來源:互聯網
上載者:User

標籤:

    Python中的字串可以是單引號‘‘或者雙引號""括起來,如果字串比較長,需要垮行,可以使用三引號‘‘‘ ‘‘‘

errHtml = ‘‘‘<HTML><HEAD><TITLE>Python CGI Demo</TITLE></HEAD><BODY><H3>ERROR</H3><B>%s</B><P><FORM><INPUT TYPE=button VALUE=BackONCLICK="window.history.back()"></FORM></BODY></HTML>‘‘‘print(errHtml)>>><HTML><HEAD><TITLE>Python CGI Demo</TITLE></HEAD><BODY><H3>ERROR</H3><B>%s</B><P><FORM><INPUT TYPE=button VALUE=BackONCLICK="window.history.back()"></FORM></BODY></HTML>

    1.格式化字串:

str1 = "name = %s, age = %d" % (‘billy‘, 28)print(str1)>>>name = billy, age = 28

  Python中的字串格式化符號與c語言的很類似:

1)%c: 格式化單個ascii字元

2)%s: 

3)%d:

4)%u:

5)%x:

6)%f:

7)%p: 用十六進位格式化變數的地址

    2. 字串常用的方法:

1)字串尋找:

    string.find(str, start=0, end=len(string));

    string.rfind;

    find方法如果找到匹配的字串,則返回起始的下標,否則返回-1。rfind與find類似,只不過是從右邊開始尋找。

str_demo = ‘hello world, just do it‘print(str_demo.find(‘just‘))print(str_demo.find(‘python‘))print(str_demo.find(‘o‘), str_demo.rfind(‘o‘))>>>13-14 19

2)字串替換: replace

    string.replace(old, new, count=string,count(old))

print(str_demo.replace(‘world‘, ‘Python‘))>>>hello Python, just do it

3)字串串連: join

#直接連接字串print(str_demo + ‘ come on‘)>>>hello Python, just do it come on
#使用join串連seqstr_nums = [‘1‘, ‘2‘, ‘3‘]sep = ‘+‘print(sep.join(str_nums))>>>1+2+3

4)字串分割:split(sep) 分割為一個list

print(str_demo.split(‘,‘))>>>[‘hello world‘, ‘ just do it‘]

5)去除字串兩邊的空格: strip

print(‘  hello world  ‘.strip())>>>hello world

6)大小寫轉換:lower, uppace

print(‘Hello World‘.lower())print(‘Hello World‘.upper())>>>hello worldHELLO WORLD


    最後,要說明的是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.