標籤:
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入門(十四) 字串