Python中的字符串用单引号 ' 或双引号 ‘’括起来,同时使用反斜杠 \ 转义特殊字符;
字符串的截取语法格式如下:
变量[头下标: 尾下标]
注:头下标为闭区间;
尾下标为开区间;
索引值以 0 为开始值, -1 为从末尾的开始位置
加号 + 是字符串的连接符,星号 * 表示复制当前字符串,紧跟的数字为复制的次数。实列如下:
另外、反斜杠(\)可以作为续行符, 表示下一行是上一行的延续。也可以使用"""…"""或者'''…'''跨越多行。
注意,Python没有单独的字符类型,一个字符就是长度为1的字符串;
与 C 字符串不同的是,Python字符串不能被改变。同一个索引位置赋值,比如 word[0] = 'm'会导致错误。
注意:
1、反斜杠可以用来转义,使用 r 可以让反斜杠不发生转义
2、字符串可以用+运算符连接在一起,用运算符重复
3、 Python中的字符串有两种索引方式,从左往右以0开始,从右往左以1开始
4、 Python中的字符串不能改变
字符串更新
可以截取字符串的一部分并与其他字段拼接,如下实例:
以上实例执行结果:
转义字符
字符串运算符
以上实例输出结果为:
字符串格式化
Python 支持格式化字符串的输出。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
在Python中,字符串格式化与 C 中 sprintf 函数一样的语法。
实例输出的结果是
字符串格式化符号:
格式化操作符辅佐命令:
三引号
Python 三引号允许一个字符串跨行,字符串中可以包含换行符、制表符以及其他特殊字符。实例如下:
以上实例执行结果为:
Unicode 字符串
在 Python2 中,普通字符串是以 8位 ASCAll 码进行存储的,而 Unicode 字符串则存储为 16位 Unicode 字符串,这样能够表示更多的字符集。使用的语法是在字符串前面加上前缀 u.
在 Python3中,所有的字符串都是 Unicode 字符串。
字符串内建函数