Python String
簡介
Python 有一個(gè)內(nèi)置的字符類str,有很多便利的特點(diǎn),字符串字符(string literals) 可以被雙引號(hào)或單引號(hào)包圍(double quotes or single quote),單引號(hào)更加常用。反斜杠轉(zhuǎn)義字符(BlackSlash esacpes)和往常一樣工作包括轉(zhuǎn)義單斜杠和雙斜杠 \n \' \" 。一個(gè)雙引號(hào)字符可以包含單引號(hào)字符而不需要任何繁瑣的步驟, 同樣一個(gè)單引號(hào)字符可以包含任何雙引號(hào)字符。一個(gè)字符字面量可以擴(kuò)展很多行,但是必須在行末添加一個(gè)反斜杠 \ 來換到新的行,在”“” (triple quotes)內(nèi)部的字符字面量可以拓展到很多行的文本。
Python 字符是 不可改變的(immutable) ,這意味著一旦他們創(chuàng)建就不可以被改變(Java strings also use this immutable style). Since strings can't be changed, we construct new strings as we go to represent computed values. 因此比如 ('hello' + 'there') takes in the 2 strings 'hello; and 'there' and build a new string "hellothere"
就像Java和C++一樣, 字符串中的字符可以通過標(biāo)準(zhǔn)的 [] 語法訪問。 Python使用從0開始的索引,比如對(duì)于 s='hello' 這一字符,s[1] 是‘e'.
當(dāng)索引超出了范圍,Python會(huì)拋出一個(gè)錯(cuò)誤(Error). Python的風(fēng)格是在無法確定要做什么的情況下就停止,而不是編造一個(gè)默認(rèn)值(Java 和C++是這樣的)。Python 也有方便的 ’slice‘切片語法,可以獲的 字符串內(nèi)的子字符串。
Python的len(string) 方法返回一個(gè)字符串的長度。[] 和len() 方法對(duì)所有的sequence type 都有效 — string ,lists , etc...Python 的風(fēng)格是盡量讓它的操作在不通過的類型間是一致的。 如果你是一個(gè)新手,注意不要用len 作為變量名而封鎖(Blocking out)掉len() 方法,+ 可以連接兩個(gè)字符串。
s = 'hi'
print (s[1]) ## i
print (len(s)) ## 2
print (s + ' there') ## hi there
對(duì)于數(shù)字來說,標(biāo)準(zhǔn)的操作符比如+,/,* 像通常一樣工作。注意在Python里面沒有++操作符,但是+=,-= 是有效的。如果你期望使用整除(integer division),可以使用兩個(gè)斜杠 // 比如6//5 是 1。
print操作會(huì)打印一個(gè)或者多個(gè)Python 對(duì)象到一個(gè)新的行, 在尾部加一個(gè),來避免(inhibit)換行。一個(gè) ”raw“字符串字面值會(huì)有一個(gè)r的前綴,raw字符會(huì)傳遞所有的字符,而不會(huì)對(duì)\ 特殊處理,也就是說r'x\nx' 會(huì)打印一個(gè)四位長的字符’x\nx' 。而一個(gè)u的前綴,允許你打印unicode 字符串(unicode 字符串包含英語以及其他語言).
>>> i = r"helllo\ninni"
>>> print(i)
helllo\ninni
multi = """It was the best of times.
It was the worst of times."""
# It was the best of times.
# It was the worst of times.
print multi
String Methods字符串方法
這里有一些最常見的字符串方法(Method). 一個(gè)方法(method)和函數(shù)一樣(function)由def 定義,只不過方法定義在對(duì)象內(nèi)部,,如果變量是一字符串 s 內(nèi),那么 s.lower() 運(yùn)行對(duì)象s內(nèi)的lower() 并且返回返回值。這里有一些常見的字符串方法:
s.lower()s.super()- returns the lowercase or upercase version of strings.strp()— returns a string with whitespace removed from the start and ends.isalpha()/s.isdigit()/s.isspace()..- tests if all the string chars are in the various character classess.staswith('other'),s.endswith('other')- tests if the string starts or ends with the given other strings.find('other')-searches for the given other string (not a regular ) within s, and return the first index where it begins or -1 if not founds.replace('old','new')—returns a string where all occurances of 'old' have been replaced by 'new's.spilt('delim')— returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text.['aaa,bbb,ccc'.spily(',')->['aaa','bbb','ccc']. As a convienient special case s.spilt() (no argument) spilts on all whitespaces cgars.-
s.join(list) — opposite of spilt(), joins the elements in the given list together using the string as the delimiter. e.g.
' —'.join(['aaa','bbb','ccc']→aaa---bbb---ccc
官方文檔Link列出了所有的str方法,Python沒有單獨(dú)的字符類型。
String Slice 字符的切片
"Slice“ 語法是一個(gè)方便的方法來引用 sequence type的一部分, 尤其是string和lists。s[start:end] 是從star延深到但 不包括end 。假設(shè)有 s="Hello"
[圖片上傳失敗...(image-90f8b1-1579105070531)]
- s[1:4] is 'ell' — chars starting at index 1 and extending up to but not include index 4
- s[1:] is 'ello' — omitting either index defaults to the start or end of the string
- s[:] is 'Hello' — omitting both always gives use a copy of the whole thing
- s[1:100] is 'ello' — an index that is too big is truncased down to the string length
標(biāo)準(zhǔn)的從0開始的索引使得容易訪問String前部的字符, 作為代替方案, Python使用附屬來更容易的讀取在在字符串末尾的字符: s[:-1] 是最后一位的字符,s[:-2]是倒數(shù)第二位(next-to-last) 的字符. 負(fù)的索引數(shù)字從字符串的尾部倒數(shù)(count back).
- s[-1] is 'o' —- last char
- s[-4] is 'e' —— 4th from the end
- s[:-3] is 'He' —- going up but not including the last 3 chars
- s[-3:] is 'llo' —- strating with the 3rd char from the end and extending to the end of the string.
對(duì)于任意一個(gè)索引n,s[:n]+ s[n:]==s .
String % 格式化字符串
Python has a printf() - 來格式化輸出一個(gè)字符串, %folowed by a format string on the left(%d int, %s string, %f/%g floating point), and the matching values in a tuple on the right(a tuple is made of values separated by commas, typically grouded inside parantheses):
# % operator
text = "%d little pigs come out, or I'll %s, and I'll %s, and I'll blow your %s down." % (3, 'huff', 'puff', 'house')
上述行比較長,假設(shè)你要把它分成很多行,你不能像在其他語言中一樣直接將其分開,因?yàn)镻ython中把每一行看成單行語句。要解決這個(gè)問題,把整個(gè)表達(dá)式包含在外面的一組括號(hào)內(nèi),那么整個(gè)表達(dá)式就會(huì)被允許分成很多行。這個(gè) code-across-lines 技術(shù)可用于下列很多種的分組構(gòu)造(),[],{}.
# Add parentheses to make the long line work:
text = (
"%d little pigs come out, or I'll %s, and I'll %s, and I'll blow your %s down."
% (3, 'huff', 'puff', 'house'))
i18n Strings (Unicode)
一般的Python字符串不是unicode, 他們只是plain bytes。為了創(chuàng)建一個(gè)unicode,使用'u'作為字符字面量的前綴:
> ustring = u'A unicode \u018e string \xf1'
> ustring
u'A unicestring"ode \u018e string \xf1'
一個(gè)unicode字符是與一般”str"字符不同的類型, 但是unicode 字符和str字符是兼容,他們有共同的超類“basestring"。如果傳遞的是unicide而不是正則字符串,很多的庫都可以正常工作。
為了把一個(gè)unicode字符串轉(zhuǎn)換成具有‘utf-8'編碼的字節(jié),可以調(diào)用ustring.encode('utf-8') 方法。反向,通過調(diào)用unicode(s,encoding) 函數(shù)把plain bytes轉(zhuǎn)換成unicode
## (ustring from above contains a unicode string)
> s = ustring.encode('utf-8')
> s
'A unicode \xc6\x8e string \xc3\xb1' ## bytes of utf-8 encoding
> t = unicode(s, 'utf-8') ## Convert bytes back to a unicode string
> t == ustring ## It's the same as the original, yay!
True
內(nèi)建的print不能完全作用與unicode,你可以首先encode() 再用utf-8編碼形式打印。在文件讀取的章節(jié)中,有一個(gè)例子允許去打開一個(gè)text文件通過一些encoding 以及read 出unicode字符串,注意Unicode在python3中有很大的不同
IF語句 IF statement
Python 不使用{ }來包圍代碼塊(比如 if/loop/function等..)相反,Python使用colon(:) 和 縮進(jìn)/空格來包圍語句。一個(gè)對(duì)于if的條件的boolean判斷不需要包括在一個(gè)括號(hào)里(這里與java和c++不同),并且可以有 "elif" 和 ”else"子句(clauses)。
任何值可以作為一個(gè)if-test的條件。一個(gè)“zero"值所有的都被算作false: none 0 empty string empty list empty dictionary .這里還有一個(gè)布爾類型包換兩個(gè)值:true 和false (轉(zhuǎn)換成
int,可以是1和0)。Python有一些常見的比較操作,==,!=
<= ,< ,<= ,>= 。不像Java和C,== 是一個(gè)重載函數(shù)(overloaded),python中它可以正確的作用于字符串。Boolean操作符在Python中是被拼寫出來的單詞 and or not .(Python不像C
使用 && || !等)。
if speed >= 80:
print 'License and registration please'
if mood == 'terrible' or speed >= 100:
print 'You have the right to remain silent.'
elif mood == 'bad' or speed >= 90:
print "I'm going to have to write you a ticket."
write_ticket()
else:
print "Let's try to keep it under 80 ok?"