目录
Strings
Python语言真正发挥作用的一个地方是字符串的操作。 本节将介绍Python的一些内置字符串方法和格式化操作。
这种字符串操作模式经常出现在数据科学工作中,并且在这种情况下是Python的一大闪光之处。
1. String syntax
在之前的课程中已经看过了很多字符串的例子,但回顾一下,Python中的字符串可以使用单引号或双引号来定义。 它们在功能上是等价的。
【1】
x = 'Pluto is a planet'
y = "Pluto is a planet"
x == y
True
如果您的字符串包含单引号字符(例如表示撇号),则使用双引号会很方便。同样,如果用单引号将其包装起来,很容易创建一个包含双引号的字符串:
【2】
print("Pluto's a planet!")
print('My dog is named "Pluto"')
Pluto's a planet!
My dog is named "Pluto"
如果我们在单引号字符串中包含单引号字母,Python会报错:
【3】
'Pluto's a planet!'
File "<ipython-input-3-16d2b0784e8c>", line 1
'Pluto's a planet!'
^
SyntaxError: invalid syntax
我们可以通过反斜杠“转义”单引号来解决这个问题。
[4]
'Pluto\'s a planet!'
"Pluto's a planet!"
下面这张表格总结了反斜杠的重要使用例子:
What you type... | What you get | example | print(example) |
---|---|---|---|
\' | ' | 'What\'s up?' | What's up? |
\" | " | "That's \"cool\"" | That's "cool" |
\\ | \ | "Look, a mountain: /\\" | Look, a mountain: /\ |
\n | "1\n2 3" | 1 2 3 |
最后一行,\n表示新的一行。
【5】
hello = "hello\nworld"
print(hello)
hello
world
此外,Python的字符串三重引用语法让我们按字面意思包括换行符(即只需在键盘上点击'Enter',而不是使用特殊的'\ n'序列)。 我们已经在文档字符串中看到了这一点,但我们可以在任何想要定义字符串的地方使用它们。
【6】
triplequoted_hello = """hello
world"""
print(triplequoted_hello)
triplequoted_hello == hello
hello
world
True
print()函数会自动添加换行符,除非我们指定关键字参数end的值而不是默认值'\ n':
【7】
print("hello")
print("world")
print("hello", end='')
print("pluto", end='')
hello
world
hellopluto
2、Strings are sequences
字符串可以看作是有序字母集合,我们可以按照对列表的操作对字符串进行操作:
【8】
# Indexing
planet = 'Pluto'
planet[0]
'P'
# Slicing
planet[-3:]
'uto'
【9】
# How long is this string?
len(planet)
5
# Yes, we can even loop over them
[char+'! ' for char in planet]
['P! ', 'l! ', 'u! ', 't! ', 'o! ']
与列表最大不同的是它们是不可以修改的。
[10]
planet[0] = 'B'
# planet.append doesn't work either
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-65a7701f8ef6> in <module>()
----> 1 planet[0] = 'B'
2 # planet.append doesn't work either
TypeError: 'str' object does not support item assignment
3、String methods
像list一样,str也有很多有趣的方法,这里有几个小例子:
[11]
# ALL CAPS
claim = "Pluto is a planet!"
claim.upper()
'PLUTO IS A PLANET!'
[12]
# all lowercase
claim.lower()
'pluto is a planet!'
[13]
# Searching for the first index of a substring
claim.index('plan')
11
[14]
claim.startswith(planet)
True
[15]
claim.endswith('dwarf planet')
False
在字符串和列表之间:.split()和.join()
str.split()将字符串拆成更小的字符串,默认情况下以空格为界;当把字符串拆分成单词列表时很有用。
[16]
words = claim.split()
words
['Pluto', 'is', 'a', 'planet!']
有时你还想除了空格以外的东西:
[17]
datestr = '1956-01-31'
year, month, day = datestr.split('-')
str.join()将我们带到另一个方向,将一个字符串列表拼接成一个长字符串,使用它作为分隔符调用的字符串。
[18]
'/'.join([month, day, year])
'01/31/1956'
[19]
# Yes, we can put unicode characters right in our string literals :)
'