個人覺得字元串實在是個比較靈活的資料格式,對其可做的操作也很多,也看了很多資料,感覺還是需要用到的時候去查查文檔,該用什麼方法好。以下是整理的一些資料,友善日後查閱。
Python Strings
Python有一個名為“str”的内置字元串類,它有許多友善的功能(有一個名為“string”的舊子產品,最好不用)。 盡管單引号更常用,但字元串文字可以用雙引号或單引号括起來。
反斜杠轉義在單引号和雙引号文字中以通常的方式工作 - 例如 \n、’、\“。雙引号字元串文字可以包含單引号而不用任何大驚小怪(例如“我沒有這樣做”)同樣單引号字元串可以包含雙引号。字元串文字可以跨越多行,但那裡 必須是每行末尾的反斜杠\才能轉義換行符。三重引号中的字元串文字"""或’’'可以跨越多行文本。
Python字元串是“不可變的”,這意味着它們在建立後無法更改(Java字元串也使用這種不可變的樣式)。 由于字元串不能更改,表示字元串計算值就是構造新字元串。 是以,例如表達式(‘hello’+‘there’)接受2個字元串’hello’和’there’并建構一個新字元串’hellothere’。
String Methods
以下是一些最常見的字元串方法。 方法就像一個函數,但它在一個對象上“運作”。 如果變量s是一個字元串,那麼代碼s.lower()在該字元串對象上運作lower()方法并傳回結果(這個在對象上運作的方法的想法是構成Object的基本思想之一——面向對象程式設計,OOP)。 以下是一些最常見的字元串方法:
- s.lower(), s.upper() – returns the lowercase or uppercase version of the string
- s.strip() – returns a string with whitespace removed from the start and end
- s.isalpha()/s.isdigit()/s.isspace()… – tests if all the string chars are in the various character classes
- s.startswith(‘other’), s.endswith(‘other’) – tests if the string starts or ends with the given other string
- s.find(‘other’) – searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
- s.replace(‘old’, ‘new’) – returns a string where all occurrences of ‘old’ have been replaced by ‘new’
- s.split(‘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’.split(’,’) -> [‘aaa’, ‘bbb’, ‘ccc’]. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
- s.join(list) – opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. ‘—’.join([‘aaa’, ‘bbb’, ‘ccc’]) -> aaa—bbb—ccc
String Slices
“切片”文法是引用序列子部分的一種友善方法 - 通常是字元串和清單。
切片s [start:end]是從開始處開始并向上延伸但不包括結束的元素。
String %
Python有一個類似printf() 的工具來組合一個字元串。%運算符在左側擷取printf類型的格式字元串(%d int,%s字元串,%f /%g浮點數),比對值在右側的元組中(元組由逗号分隔的值組成,通常在括号内分組):
# % 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')
More operations
keep updating…
References
- http://www.runoob.com/python3/python3-string.html
- https://www.jb51.net/article/151093.htm