Python 101: 和字符串相關的經常使用操做

若是你正在找一個輕鬆愉快,但又緊湊高效的Python視頻,Python 101這個系列就是專門爲你設計的。咱們會以一個開發者理解編程語言的視角,向你們完整介紹Python語言自己、Python標準庫、如何使用Python編寫經常使用的代碼片斷、以及如何管理和發佈你的Python代碼。現現在,Python已經成爲了AI領域最煊赫一時的編程語言,不管你手頭的工做是否會用到Python,這絕對都是值得投資的一項編程技能。Don't hesitate, let's go.python

和字符串相關的經常使用操做

泊學4K視頻學習
泊學閱讀文檔git

在Python中,最經常使用的一類數據類型,莫過於字符串了。在接下來的兩小節內容裏,咱們就來分享和字符串相關的各類最經常使用的操做。編程

如何建立一個字符串

咱們先來看如何建立字符串。和其餘弱若類型腳本語言同樣,咱們能夠用單引號或雙引號建立字符串:api

stringInDoubleQuotes = "Hello Python!"
stringInSingleQuotes = 'Hello Python!'

或者,若是字符串的內容須要跨過多行,還可使用「三引號」的形式:數組

stringInTripleQuotes = '''Hello Python!
This might be a long string
going through multiple lines.
'''

基於這樣的用法,若是咱們要在字符串中使用雙引號,就把它放在單引號包圍的字符串裏,反之亦然:app

stringInDoubleQuotes = "Hello 'Python'!"
stringInSingleQuotes = 'Hello "Python"!'

而且,咱們還能夠在「三引號」包圍的字符串裏,使用單引號和雙引號:ssh

stringInTripleQuotes = '''Hello 'Python'!
This might be a "long string"
acrossing multiple lines.
'''

除了直接用字面值建立字符串以外,咱們還能夠用數字類型建立字符串:編程語言

aNumber = 123
aString = str(number)

可是,用字符串建立數字類型的操做,卻不必定總能成功。例如,下面的代碼,就會致使一個運行時錯誤:ide

error = int('abc')

'''
Traceback (most recent call last):
  File "/Users/puretears/Desktop/tmp/aa.py", line 2, in <module>
    int('abc')
ValueError: invalid literal for int() with base 10: 'abc'
'''

只有當字符串的字面值真的表示一個數字的時候,轉換才能夠完成:學習

oneTwoThree = int("123")

另外,字符串在Python中是隻讀的。一旦建立完成,就不能像C語言同樣用位置去修改了。例如,下面的代碼,也會致使編譯錯誤:

aString[0] = 0

'''
Traceback (most recent call last):
  File "/Users/puretears/Desktop/tmp/aa.py", line 2, in <module>
    aString[0] = 0
TypeError: 'str' object does not support item assignment
'''

最後一個關於字符串建立要說明的是,在Python 2和Python 3中,默認使用的字符編碼是不一樣的。Python 2中,使用的是ASCII編碼,爲了使用unicode編碼,須要明確在字符串前面使用小寫字母u,像這樣:

stringInDoubleQuotes = u"Hello Python!"

雖然,這樣的語法在Python 3中也適用,但卻不必這樣。由於Python 3的字符串,默認使用的就是unicode編碼。

經常使用的字符串操做

瞭解瞭如何建立字符串以後,咱們來看一些經常使用的字符串操做,它們大多都簡單易行。

首先,咱們能夠用加號直接鏈接兩個字符串:

action = "Hello "
name = "Mars!"
welcome = action + name # Hello Mars!

其次,咱們能夠直接對字符串使用upper()lower()方法轉換字符串的大小寫:

welcome.upper() # hello mars!
welcome.lower() # HELLO MARS!

第三,咱們能夠用stripe()方法直接去掉字符串的首尾空格:

action.strip()

獲取API幫助信息

若是咱們要查看字符串類型支持的全部方法,可使用dir方法:

print(dir(action))

'''
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
'''

這樣,咱們就會獲得一個數組,包含了字符串支持的全部操做。若是要查看某個方法的具體幫助,可使用help方法:

print(help(action.count))

'''
count(...) method of builtins.str instance
    S.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are
    interpreted as in slice notation.
'''

這樣,咱們就能夠看到方法的簽名,以及一個簡短的描述信息了。

分割字符串

從上面count的描述信息能夠看到,它接受一個形如S[start:end]這樣的參數,在Python裏,這叫作String slicing。當咱們對字符串類型使用[]操做符的時候,既能夠像C同樣,使用單個字符的位置讀取內容:

action[0] # H

也可使用一個range,截取字符串的一部分:

hello = action[0:5] # Hello

要說明的是,在Python裏,0:5這樣的寫法,是一個半閉半開區間,就如同Swift中的0..<5同樣。所以,hello的值,是字符串Hello,而不是Hello加上一個空格。

What's next?

以上,就是這一節的內容,咱們瞭解了字符串的建立、經常使用操做以及獲取API幫助的方式。實際上,除了單純的使用字面值或者數字以外,咱們還可使用某種形式的模板,定製字符串的內容,這叫作string template,在下一節,咱們就來了解它的兩種不一樣用法。

相關文章
相關標籤/搜索