Python 2.6 非程式設計師教程/字串復仇
現在展示一個可以用字串完成的酷技巧
def shout(string):
for character in string:
print "Gimme a " + 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 a L 'L' Gimme a o 'o' Gimme a s 's' Gimme a 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 到 255 的數字。Python 有一個名為ord()(表示序數)的函式,它將字元作為數字返回。還有一個對應的名為chr()的函式,它將數字轉換為字元。考慮到這一點,程式應該開始變得清晰。第一個細節是這行程式碼:if 'a' <= character <= 'z':,它檢查一個字母是否為小寫字母。如果是,則使用下一行程式碼。首先,它被轉換為一個位置,以便 a = 0,b = 1,c = 2 等等,使用這行程式碼:location = ord(character) - ord('a')。接下來,使用new_ascii = location + ord('A') 找到新的值。此值被轉換回現在為大寫的字元。
現在進行一些互動式打字練習
>>> # Integer to String
>>> 2
2
>>> repr(2)
'2'
>>> -123
-123
>>> repr(-123)
'-123'
>>> `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
>>> `float("1.23")`
'1.23'
如果你還沒有猜到,函式repr()可以將整數轉換為字串,函式int()可以將字串轉換為整數。函式float()可以將字串轉換為浮點數。repr()函式返回某個物件的打印表示形式。`...` 也會將幾乎所有內容轉換為字串。以下是一些示例:
>>> repr(1) '1' >>> repr(234.14) '234.14' >>> repr([4, 42, 10]) '[4, 42, 10]' >>> `[4, 42, 10]` '[4, 42, 10]'
int() 函式嘗試將字串(或浮點數)轉換為整數。還有一個類似的函式叫做float(),它會將整數或字串轉換為浮點數。Python 擁有的另一個函式是eval() 函式。eval() 函式接收一個字串並返回 Python 認為它找到的型別的資料。例如
>>> 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] 給我們剪下位置 1 和 4 之間的整個text 字串,“TRI”。如果你省略了 [first_index:last_index] 引數之一,則預設情況下你會得到字串的開頭或結尾:text[:5] 給出“STRIN”。對於first_index 和last_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 = chr(ord('0') + in_int % 10) + out_str
in_int = in_int / 10
out_str = chr(ord('0') + 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 x in range(0, len(in_str)):
out_num = out_num * 10 + ord(in_str[x]) - ord('0')
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