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_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