字符串创建
使用引号( ' 或 " )来创建字符串,赋给变量。
字符串访问
没有单独的字符类型;一个字符就是长度为一的字符串
访问子字符串,可以使用[:]方括号来截取字符串,
字符串更新——截取字符串的一部分并与其他字段拼接(“+”)
分切索引(截取字符串)的工作方式,想像索引是指向字符之间,第一个字符左边的数字是 0。接着,有n个字符的字符串最后一个字符的右边是索引n,例如:

在字符串内部使用特殊字符时,用反斜杠(\)转义字符:

字符串运算符:


字符串格式化
最基本的用法是将一个值插入到一个有类似字符串格式符 %s 的字符串中,语法:
" %s %d...%d " % (var1, var2,...,varn)


另外一种方法是:格式化字符串的函数 str.format(),基本语法是通过 {} 和 : 来代替以前的 %,可以接受不限个参数,{}中设置对应到format()中参数的位置


对象也可以作为 str.format() 的参数:

str.format()数字格式化:

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制。
此外我们可以使用大括号 {} 来转义大括号,如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print ("{} 对应的位置是 {{0}}".format("runoob"))
输出结果为:runoob对应的位置是{0}
三引号(triple quotes)
三引号可以将复杂的字符串进行复制而存在,即所谓的WYSIWYG(所见即所得)格式的:三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符,语法是一对连续的单引号或者双引号(成对的用)。如下:
cursor.execute('''
CREATE TABLE users (
login VARCHAR(8),
uid INTEGER,
prid INTEGER)
''')
errHTML = ''' <HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>ERROR</H3> <B>%s</B><P> <FORM><INPUT TYPE=button VALUE=Back ONCLICK="window.history.back()"></FORM> </BODY></HTML> '''
Unicode 字符串
在Python3中,所有的字符串都是Unicode字符串。
字符串内置方法(直接使用,不需要导入)







网友评论