python基础知识之列表与字符串比较

it2026-08-16  8

python基础知识之列表与字符串比较


python中的列表与字符串有共同之处 都是序列,可以进行索引和片选等。

>>> s="python" >>> lst=['p','y','t','h','o','n'] >>> s[1:3] 'yt' >>> lst[1:3] ['y', 't'] >>> s[-1] 'n' >>> lst[-2] 'o'

python中的列表与字符串有不同之处 1.列表可变,字符串不可变

>>> s="python" >>> lst=['p','y','t','h','o','n'] >>> s[1]='A' Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> s[1]='A' TypeError: 'str' object does not support item assignment >>> lst[1]='A' >>> lst ['p', 'A', 't', 'h', 'o', 'n']

2.字符串的元素只能是字符,而列表可以是任意对象。 python中的列表与字符串可以相互转化

>>> s="python" >>> lst=['p','y','t','h','o','n'] >>>> "".join(lst) 'python' >>> list(s) ['p', 'y', 't', 'h', 'o', 'n']
最新回复(0)