跳轉到內容

Python 3 非程式設計師教程/字串復仇

來自華夏公益教科書

現在介紹一個可以用字串實現的酷炫技巧

def shout(string):
    for character in string:
        print("Gimme an " + character)
        print("'" + character + "'")

shout("Lose")

def middle(string):
    print("The middle character is:", string[len(string) // 2])

middle("abcdefg")
middle("The Python Programming Language")
middle("Atlanta")

輸出結果是

Gimme an L
'L'
Gimme an o
'o'
Gimme an s
's'
Gimme an e
'e'
The middle character is: d
The middle character is: r
The middle character is: a

這些程式演示了字串在很多方面與列表類似。shout() 函式表明,for 迴圈可以像用於列表一樣用於字串。middle 過程表明,字串也可以使用 len() 函式、陣列索引和切片。大多數列表功能也適用於字串。

下一個功能演示了一些特定於字串的功能

def to_upper(string):
    ## Converts a string to upper case
    upper_case = ""
    for character in string:
        if 'a' <= character <= 'z':
            location = ord(character) - ord('a')
            new_ascii = location + ord('A')
            character = chr(new_ascii)
        upper_case = upper_case + character
    return upper_case

print(to_upper("This is Text"))

輸出結果是

THIS IS TEXT

這是因為計算機將字串的字元表示為從 0 到 1,114,111 的數字。例如,'A' 是 65,'B' 是 66,而 א 是 1488。這些值是 Unicode 值。Python 有一個名為 ord()(代表序數)的函式,它將字元作為數字返回。還有一個對應的名為 chr() 的函式,它將數字轉換為字元。考慮到這一點,程式應該開始變得清晰。第一個細節是這行程式碼:if 'a' <= character <= 'z':,它檢查字母是否為小寫。如果是,則使用接下來的幾行程式碼。首先將其轉換為位置,以便 a = 0,b = 1,c = 2,依此類推,使用這行程式碼:location = ord(character) - ord('a')。接下來使用 new_ascii = location + ord('A') 找到新值。此值將轉換回現在是大寫的字元。請注意,如果您確實需要字母的大寫形式,您應該使用 u=var.upper(),它也可以用於其他語言。

現在進行一些互動式打字練習

>>> # Integer to String
>>> 2
2
>>> repr(2)
'2'
>>> -123
-123
>>> repr(-123)
'-123'
>>> # String to Integer
>>> "23"
'23'
>>> int("23")
23
>>> "23" * 2
'2323'
>>> int("23") * 2
46
>>> # Float to String
>>> 1.23
1.23
>>> repr(1.23)
'1.23'
>>> # Float to Integer
>>> 1.23
1.23
>>> int(1.23)
1
>>> int(-1.23)
-1
>>> # String to Float
>>> float("1.23")
1.23
>>> "1.23" 
'1.23'
>>> float("123")
123.0

如果您還沒有猜到,repr() 函式可以將整數轉換為字串,而 int() 函式可以將字串轉換為整數。float() 函式可以將字串轉換為浮點數。repr() 函式返回某個物件的打印表示形式。以下是幾個示例

>>> repr(1)
'1'
>>> repr(234.14)
'234.14'
>>> repr([4, 42, 10])
'[4, 42, 10]'

int() 函式嘗試將字串(或浮點數)轉換為整數。還有一個類似的函式名為 float(),它將整數或字串轉換為浮點數。Python 還有另一個函式名為 eval() 函式。eval() 函式接受一個字串,並返回 Python 認為找到的型別的 data。例如

>>> v = eval('123')
>>> print(v, type(v))
123 <type 'int'>
>>> v = eval('645.123')
>>> print(v, type(v))
645.123 <type 'float'>
>>> v = eval('[1, 2, 3]')
>>> print(v, type(v))
[1, 2, 3] <type 'list'>

如果您使用 eval() 函式,您應該檢查它是否返回了您預期的型別。

一個有用的字串函式是 split() 方法。以下是一個示例

>>> "This is a bunch of words".split()
['This', 'is', 'a', 'bunch', 'of', 'words']
>>> text = "First batch, second batch, third, fourth"
>>> text.split(",")
['First batch', ' second batch', ' third', ' fourth']

請注意 split() 如何將字串轉換為字串列表。字串預設情況下按空格分割,或者按可選引數(在本例中為逗號)分割。您還可以新增另一個引數,告訴 split() 分隔符將被用來分割文字多少次。例如

>>> list = text.split(",")
>>> len(list)
4
>>> list[-1]
' fourth'
>>> list = text.split(",", 2)
>>> len(list)
3
>>> list[-1]
' third, fourth'

字串切片(以及列表)

[編輯 | 編輯原始碼]

字串可以像前面章節中對列表所展示的那樣,使用切片“運算子”切割成片段。[]。切片運算子的工作方式與之前相同:text[first_index:last_index](在極少數情況下可能會有另一個冒號和第三個引數,如以下示例所示)。

為了避免索引號混淆,最簡單的方法是將其視為剪下點,將字串切分成部分的可能性。以下是一個示例,它顯示了簡單文字字串的剪下點(黃色)及其索引號(紅色和藍色)

0 1 2 ... -2 -1
text = " S T R I N G "
[: :]

請注意,紅色索引從字串的開頭開始計數,而藍色索引從字串的結尾反向計數。(請注意,字串末尾沒有藍色 -0,這似乎是合乎邏輯的。因為-0 == 0,-0 也表示“字串的開頭”。)現在我們可以使用索引進行切片操作

text[1:4] "TRI"
text[:5] "STRIN"
text[:-1] "STRIN"
text[-4:] "RING"
text[2] "R"
text[:] "STRING"
text[::-1] "GNIRTS"

text[1:4]為我們提供所有text剪下點 1 和 4 之間的字串,"TRI”。如果您省略了 [first_index:last_index] 引數之一,則預設情況下會獲得字串的開頭或結尾text[:5]給出 "STRIN”。對於兩者first_indexlast_index我們可以使用紅色和藍色編號方案text[:-1]text[:5]相同,因為在本例中,索引 -1 與 5 在相同的位置。如果我們不使用包含冒號的引數,則數字將以不同的方式處理text[2]為我們提供第二個剪下點後的一個字元,"R”。特殊的切片操作text[:]表示“從開頭到結尾”,並生成整個字串(或列表,如上一章所示)的副本。

最後但並非最不重要的一點是,切片操作可以有第二個冒號和第三個引數,它被解釋為“步長”text[::-1]text從開頭到結尾,步長為 -1。-1 表示“每個字元,但方向相反”。"STRING"反過來是 "GNIRTS"(如果您還沒有明白,請測試一下步長為 2 的情況)。

所有這些切片操作也適用於列表。從這個意義上說,字串只是列表的一種特殊情況,其中列表元素是單個字元。只要記住剪下點的概念,切片事物的索引就會變得不那麼令人困惑。

# This program requires an excellent understanding of decimal numbers.
def to_string(in_int):
    """Converts an integer to a string"""
    out_str = ""
    prefix = ""
    if in_int < 0:
        prefix = "-"
        in_int = -in_int
    while in_int // 10 != 0:
        out_str = str(in_int % 10) + out_str
        in_int = in_int // 10
    out_str = str(in_int % 10) + out_str
    return prefix + out_str

def to_int(in_str):
    """Converts a string to an integer"""
    out_num = 0
    if in_str[0] == "-":
        multiplier = -1
        in_str = in_str[1:]
    else:
        multiplier = 1
    for c in in_str:
        out_num = out_num * 10 + int(c)
    return out_num * multiplier

print(to_string(2))
print(to_string(23445))
print(to_string(-23445))
print(to_int("14234"))
print(to_int("12345"))
print(to_int("-3512"))

輸出結果是

2
23445
-23445
14234
12345
-3512
Python 3 非程式設計師教程
 ← 更多關於列表 字串復仇 檔案 I/O → 
華夏公益教科書