专业编程基础技术教程

网站首页 > 基础教程 正文

Python 字符串

ccvgpt 2025-05-25 11:12:46 基础教程 1 ℃

除了数字,Python还可以操作字符串。字符串的形式是单引号('......')双引号(''.........'')或三个单引号('''..........''')

>>> 'spam and eggs '
'spam and eggs '
>>> 'doesn\'t'
"doesn't"
>>> 'py' + 'thon'
'python'
>>> word = 'pyhton'
>>> word[0]
'p'
>>> word[2]
'h'
>>> word[-1]
'n'

1、用 + 号合并字符串,2、字符串支持索引 word[1] ,3、字符串还支持负数索引 word[-1]

Python 字符串

>>> word[0:2]
'py'
 ----------------------
  p  y   t    h    o   n 
 ----------------------
 0   1   2   3   4   5   6   (0-5是整数索引的位置 6 是字符串的长度)
-6  -5  -4  -3  -2  -1    (-1 到 -6是负数的索引位置)

1、Python也支持切片,索引可以提取单个字符,而切片却可以提取多个字符,注意输出结果包括切片开始,但不包括切片结束。

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

>>> a = 'abcdefghijklmnopqrstuvwxyz'
>>> len(a)
26

2、Python字符串不能修改,只能从新定义。3、函数 len() 返回值是字符串的长度。

最近发表
标签列表