Python 中所有序列都可以进行一些特定操作,包括索引(indexing)、分片(slicing)、序列相加(adding)、乘法(multiplying)、成员资格、长度、最小值和最大值。
所有的序列(例如:字符串、列表)都可以进行以下基本操作:
+
:连接两个序列*
:重复序列元素in
:判断元素是否在序列中min()
:返回最小值max()
:返回最大值len()
:返回序列长度enumerate()
:返回一个枚举对象,包含字符串中所有元素的索引和值(作为一对)字符串(String),是由零个或多个字符组成的有限序列,在 Python 中表示文本的数据类型。
字符只是一个符号,例如:字母(A-Z)、数字(0-9)、特殊符号(~!@#¥%…)等。
在 Python 中,字符串由内置的 str 类型定义。
>>> s=" hello world"
>>> type(s)
可以使用单引号(''
)或双引号(""
)来表示字符串。
PS: 单引号比双引号更常用。
字符串可以跨多行,但是每行末尾必须添加反斜杠(\
)以转义换行符。
>>> s= 'Hello \
... World'
>>> s
'Hello World'
三重引号('''
或 """
)内的字符串可以跨多个文本行。
>>> s = '''Hello #三重单引号
... World'''
>>> s
'Hello \nWorld'
>>> s = """Hello #三重双引号
... World"""
>>> s
'Hello \nWorld'
注意: 三重引号通常用于表示多行字符串和 docstring。
序列是 Python 中最基本的数据结构。序列中的每个元素都分配一个数字,代表它在序列中的位置(索引),第一个索引是 0 ,第二个索引是 1,以此类推。
【注】其中,length 为字符串的长度。
【例】
>>> s='Hello'
>>> s[0] #第一个字符
'H'
>>> s[4] #最后一个字符
'o'
>>> s[-5] #第一个字符
'H'
>>> s[-1] #最后一个字符
'o'
>>> s[5] #索引必须在范围内
Traceback (most recent call last):
File "", line 1, in
IndexError: string index out of range
>>> s[1.5] #索引必须是整数
Traceback (most recent call last):
File "", line 1, in
TypeError: string indices must be integers
【注】不定义变量也可以进行字符串的索引,也可以直接对函数的返回结果进行索引操作。
>>> 'Hello'[0]
'H'
>>> 'Hello'[-1]
'o'
>>> s=input()[1]
Hello
>>> print(s)
e
切片操作(slice)是用于引用序列(通常是字符串和列表)的子部分。
切片操作的语法格式:
[start:stop:step]
>>> number=[1,2,3,4,5,6,7,8,9,10]
>>> number[1:3] #取索引为1、2的元素
[2, 3]
>>> number[-3:-1] #负数表示从右开始计数,取索引为-3、-2的元素
[8, 9]
>>> number[3:10] #stop大于最大的索引,将取到结束为止
[4, 5, 6, 7, 8, 9, 10]
>>> number[3:] #第 4 个字符到最后一个
[4, 5, 6, 7, 8, 9, 10]
>>> number[:] #所有字符
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> number[:-3] #开始到倒数第三
[1, 2, 3, 4, 5, 6, 7]
>>> number[-3:] #倒数第三到最后一个字符
[8, 9, 10]
>>> number[:0] #最后一个元素为第一个,输出为空
[]
>>> number[::2] #步长为2,得到奇数序列
[1, 3, 5, 7, 9]
>>> number[2:6:3] #将每三个元素的第一个提取出来
[3, 6]
>>> number[::0] #步长不能为0
Traceback (most recent call last):
File "", line 1, in
ValueError: slice step cannot be zero
>>> number[10:0:-2] #步长为负数
[10, 8, 6, 4, 2]
>>> number[0:10:-2] #步长为负数
[]
>>> number[::-2]
[10, 8, 6, 4, 2]
>>> number[2::-1]
[3, 2, 1]
s[:n] + s[n:] == s
是一个整齐的切片,甚至对于负数或超出界限的值也是如此。换一种说法,s[:n]
和 s[n:]
总是将字符串分成两部分,来保存所有的字符。使用加号可以进行序列的连接操作。
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a+b
[1, 2, 3, 4, 5, 6]
>>> s='Hello'
>>> s2=" World"
>>> s+s2
'Hello World'
>>> [1,2,3]+'Hello'
Traceback (most recent call last):
File "", line 1, in
TypeError: can only concatenate list (not "str") to list
>>> [1,2,3]+[3,4,5]
[1, 2, 3, 3, 4, 5]
使用数字 n 乘以一个序列会生成新的序列,在新的序列中,原来的序列将被重复 n 次。
>>> s=[1,2,3]
>>> s*5
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> "zth"*5
'zthzthzthzthzth'
>>> sq=[None]*5 #初始化 sq 为含有 5 个 None 的序列
>>> sq
[None, None, None, None, None]
可以使用 in
运算符判断一个对象是否为某个序列的成员(元素)。
>>> 'h' in 'Hello'
False
>>> 'e' in 'Hello'
True
>>> 1 in [1,2,3]
True
dataBase = [["wangjian","1234"],["zhangjian","1234"],["wanglin","1234"],["wangxin","1234"]];
userName = input("请输入姓名:");
userPass = input("请输入密码:");
if([userName,userPass] in dataBase):
print("输入的用户名和密码存在");
else:
print("输入的用户名和密码不存在");
Python 的内建函数:len/min/max
的作用分别是:返回序列中包含元素的数量,返回序列中最小和最大元素。
>>> li=[235,26,164,3]
>>> len(li)
4
>>> max(li)
235
>>> min(li)
3
>>> max(5,56,23,123)
123
>>> len("Hello")
5
>>> min("Hello");
'H'
>>> max("Hello")
'o'
字符串是不可变的,也就是说,一旦分配了字符串的元素就不能被更改。
但是,可以将不同的字符串重新分配给同一个变量。
>>> s = 'Hello'
>>> s[2] = 'a'
...
TypeError: 'str' object does not support item assignment
>>>
>>> s = 'Python'
>>> s
'Python'
无法从字符串中删除字符,但是可以使用关键字 del
完全删除字符串。
>>> del s[2]
...
TypeError: 'str' object doesn't support item deletion
>>>
>>> del s
>>> s
...
NameError: name 's' is not defined
使用 for 循环,可以遍历一个字符串。
>>> count = 0;
>>> for letter in 'Hello':
... if(letter == 'e'):
... count += 1
...
>>> print(count)
1
还可使用 enumerate(),它会返回一个枚举对象,包含字符串中所有元素的索引和值(作为一对),这对于迭代很有用。
>>> s = 'Hello'
>>> e = set(enumerate(s))
>>> print(e)
{(4, 'o'), (0, 'H'), (1, 'e'), (3, 'l'), (2, 'l')}
>>> for index ,item in e:
... print(index,item)
...
4 o
0 H
1 e
3 l
2 l
字符串有许多方法,可以通过 dir() 来查看方法列表:
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
利用 help() 函数,可以查看函数或模块用途的详细说明:
>>> help(str.lower)
Help on method_descriptor:
lower(self, /)
Return a copy of the string converted to lowercase.
注意: 要终止查询,使用 q 键。
按照说明,可以在交互模式下进行实验,这里仅列举一些比较常用的方法。
>>> s = 'Hello'
>>>
>>> s.lower() # 转换所有字符为小写
'hello'
>>>
>>> s.upper() # 转换所有字符为大写
'HELLO'
>>>
>>> s.find('ll') # 返回子串的开始索引
2
>>>
>>> s.endswith('llo') # 检查字符串是否以指定的子串结束
True
>>>
>>> s.isdigit() # 检查字符串是否只包含数字
False
>>>
>>> s.replace('ll', 'r') # 替换字符串中的子串
'Hero'
>>>
>>> s = 'I like Python'
>>>
>>> s.split() # 分割字符串
['I', 'like', 'Python']