使用 Linkbot 學習 Python 3/字串的復仇
現在展示一個可以用字串完成的酷炫技巧
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 到 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 認為它找到的型別的資料。例如
>>> 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_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 = 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