Python 字符串

字符串也是Python中的一种基本数据类型,字符串表示字符的有序集合。

与C语言不同,在Python中,没有单个字符,Python中使用有一个字符的字符串来表示字符。在Python中,单行的字符串可以使用单引号、双引号来表示,两者都可以使用,

多行字符串采用三重引号:

>>> str1="hello world"
>>> str2 = 'hello world'
>>> str3 = ''' hello
... world
... !'''
>>> str1
'hello world'
>>> str2
'hello world'
>>> str3
' hello\nworld\n!'
>>> print str3
 hello
world
!

我们可以在一个双引号字符串中嵌入单引号字符,同样,也可以在单引号字符串中嵌入一个双引号字符。

>>> "hello,what's your name"
 "hello,what's your name"
>>> 'hello,"world'
 'hello,"world'

字符串长度

可以通过Python内置的len()函数来计算字符串的长度,即含有字符的个数:

>>> len("hello")
5

Python中字符串与C语言是不一样的,C语言中会有一个’\0’表示字符串结束符号。所以hello的长度是5而不是6.

字符串索引和合并

Python中,字符串不可以在实地进行修改,如果要修改的话,只能新定义一个字符串,然后通过合并、切片等工具进行操作。

字符串通过[]来进行索引,我们通过其位置可以获取到其对应的元素,字符串的偏移量是从0开始的。Python还支持负偏移,把负偏移认为是从结束处反向计数。通过“+”来进行合并操作:

>>> str = 'hello' + 'world'
>>> str
'helloworld'
>>> str[0]
'h'
>>> str[1]
'e'
>>> str[-1]
'd'
>>> str[-2]
'l'

字符串的切片

如果我们想从字符串中提取一部分子字符串,就可以通过切片来实现。当我们使用一对以冒号分隔的偏移索引对字符串进行操作时,返回的就是一个新的子字符串对象。左边的偏移成为下边界,右边的偏移称为上边界。如果被省略,默认就是0和切片对象的长度。

>>> str = 'world'
>>> str[:]
'world'
>>> str[1:]
'orld'
>>> str[:3]
'wor'
>>> str[1:3]
'or'

同样,切片也支持负偏移操作。

>>> str[-1:3]
''
>>> str[-4:3]
'or'
>>> str[-3:3]
'r'
>>> str[-5:3]
'wor'

Python中,字符串不支持在实地进行修改,只能通过切片、合并等操作去生成一个新字符串来完成:

>>> str='hello'
>>> str[0]
'h'
>>> str[0]='f'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

字符串格式化

与C语言的printf函数类似,Python提供了%来对字符串的值进行格式化。在%操作符的左侧放置一个需要格式化的字符串,在%的右侧放置一个对象,这个对象将会插入到左侧想让Python进行格式化字符串转换目标的位置上去。

>>> "my name is %s, I am %d years old"%('Daydayman',20)
'my name is Daydayman, I am 20 years old'

字符串比较

字符串支持通常的比较操作符<、

>>> "hello" == "hello"
True
>>> "hello" > "hello"
False
>>> "hello" > "hellp"
False
>>> "hello" != "hellp"
True
>>> "hello" > "hell"
True

字符串方法

字符串除了支持基本的表达式运算外,还提供了一系列的方法实现更负责的文本处理任务。方法就是与特定的对象相关联在一起的函数。

>>> str = 'hello'
>>> str.isdigit()
False
>>> str.upper()
'HELLO'
>>> str.replace('h','H')
'Hello'
>>> str.find('ell')
1
>>> str.find('l')
2
>>> str.split('l')
['he', '', 'o']
《Linux三剑客》视频教程,从零开始快速掌握Linux开发常用的工具:Git、Makefile、vim、autotools、debug,免费赠送C语言视频教程,C语言项目实战:学生成绩管理系统。详情请点击淘宝链接:Linux三剑客