字符串类型
函数
str(x) #返回一个字符串,x-可以转换为字符串的数据类型
字符串是使用引号创建的,可以使用单引号,也可以使用双引号,但是字符串两端必须相同
在引号包含的字符串中使用引号,使用的引号与包含字符串的引号不同时,直接使用该引号,如果相同,就必须对其进行转义
>>>a = "Single 'quotes' are fine; \"doubles\" must be escaped."
>>>b = 'Single \'quotes\' must be escaped; "doubles" are fine.'
Python字符串转义
\newline #忽略换行
\\ #反斜杠(\)
\' #单引号(')
\" #双引号(")
\a #ASCII蜂鸣(BEL)
\b #ASCII退格(BS)
\f #ASCII走纸(FF)
\n #ASCII换行(LF)
\N{name} #给定名称的Unicode字符
\ooo #给定八进制值的字符
\r #ASCII回车符(CR)
\t #ASCII制表符(TAB)
\uhhhh #给定16位十六进制值的Unicode字符
\Uhhhhhhhh #给定32位十六进制值的Unicode字符
\v #ASCII垂直指标(VT)
\xhh #给定8位十六进制值的Unicode字符
如果要写一个长字符串,跨越了多行,有两种方法
>>>t = "This is not the best way to join two long strings" + \
"together since it relies on ugly newline escaping"
>>>s = ("This si the nice way to join two long strings"
"together; it relies on string literal concatenation.")
注意:字符串s不使用圆括号,会导致IndentationError异常
由于Python文件默认使用UTF-8 Unicode编码,可以在字符串中写入任意Unicode字符
>>>euros = "ε\N{euro sign}\u20AC\U000020AC"
>>>print(euros)
εεεε
ord(x) #返回x的ASCII值,如ord('A') = 65
chr(x) #返回ASCII值x所对应的单字符串
比较操作符
<、<=、==、!=、>和>=
切片
seq[start:end:step] #step为-1,每个字符都将被提取,方向从终点到起点,产生反转的字符串
>>>s = "he ate camel food";
>>>s[-1:2:-2]
'do ea t'
方法
s.capitalize() #返回字符串s的副本,将首字符变成大写
s.center(width, char) #返回s中间部分的一个子字符串,长度为width,并使用空格或可选的char(长度为1的字符串)进行填充,同s.ljust()、s.rjust()一样的用法
s.count(t, start, end) #返回字符串s中(或在s的切片中)子字符串t出现的次数
s.encode(encoding, err) #返回一个bytes对象,该对象使用默认的编码格式或指定的编码格式来表示该字符串,并根据可选的err参数处理错误
s.endwith(x, start, end) #如果s(或在s的切片中)以字符串x结尾,就返回true,否则返回false,同s.startwith()一样
s.expandtabs(size) #返回s的一个副本,其中的制表符使用8个或指定数量的空格替换
s.find(t, start, end) #返回t在s中(或在s的切片中)的最左位置,如果没有找到,就返回-1,同s.index()一样,s.rfind()是发现最右边位置
s.format(x) #返回给定参数进行格式化后的字符串副本
>>>x = "three";
>>>s = "{0}{1}{2}";
>>>s = s.format("The", x, "tops"); #连接字符串
>>>s
'The three tops'
>>>"{who} turned {age} this year".format{who = "She", age = 88};
'She turned 88 this year'
>>>stock = ["paper", "envelopes". "notepads", "pens", "paper clips"];
>>>"We have {0[1]} and {0[2]} in stock".format(stock);
'We have envelopes and notepads in stock'
>>>d = dict(animal = "elephant", weight = 12000)
>>>"The {0[animal]} weighs {0[weight]}kg".format(d)
'The elephant weighs 12000kg'
>>>"{} {} {}".format("Python", "can", "win");
Python can win
>>>element = "Silver"
number = 47
"Element {nmber} is {element}".format(**locals())
'Element 47 is Silver'
#s-用于强制使用字符串形式;r-用于强制使用表象形式;a-用于强制使用表象形式,仅限于ASCII字符
>>>"{0} {0!s} {0!r} {0!a}".format(decimal.Decimal("93.4"))
"93.4 93.4 Decimal('93.4') Decimal('93.4')"
s.index(t, start, end) #返回t在s中的最左边位置(或在s的切片中),如果没有找到,就产生ValueError异常。s.rindex()从右边开始搜索
s.isalnum() #如果s非空,并且其中的每个字符都是字母数字的,就返回true
s.isalpha() #如果s非空,并且其中的每个字符都是字母的,就返回true
s.isdecimal() #如果s非空,并且其中的每个字符都是Unicode的基数为10的数字,就返回true
s.isdigit() #如果s非空,并且每个字符都是一个ASCII数字,就返回true,不能因为isdigit()函数返回true就判断某个字符串可以转换为整数
s.isidentifier() #如果s非空,并且是一个有效的标识符,就返回true
s.islower() #如果s至少有一个可小写的字符,并且其所有可小写的字符都是小写的,就返回true
s.isupper() #如果s至少有一个可大写的字符,并且其所有可大写的字符都是大写的,就返回true
s.isnumeric() #如果s非空,并且其中的每个字符都是数值型的Unicode字符,比如数字或小数,就返回true
s.isprintable() #如果s非空,并且其中的每个字符被认为是可打印的,包括空格,但不包括换行,就返回true
s.isspace() #如果s非空,并且其中的每个字符都是空白字符,就返回true
s.istitle() #如果s是一个非空的首字母大写的字符串,就返回true
s.join(seq) #返回序列seq中每个项连接起来后的结果,并以s(可以为空)在每两项之间分隔
>>>treatises = ["Arithmetica", "Conics", "Elements"];
>>>"".join(treatises)
'ArithmeticaConicsElements'
s.split(t, n) #返回一个字符串列表,在字符串t处之多分割n次,如果没有给定n,就分割尽可能多次,如果t没有给定,就在空白处分割。s.rsplit()从右边进行分割
>>>record = "Leo Toistoy*1828-8-28*1910-11-20";
>>>fields = record.split("*");
>>>fields
['Leo Tolstoy', '1828-8-28', '1910-11-20']
s.lower() #将s中的字符变为小写
s.upper() #将s中的字符变为大写
s.partition(t) #返回包含3个字符串的元组——字符串s在t的最左边之前的部分、t、字符串s在t之后的部分。如果t不在s内,则返回s与两个空字符串。使用s.rpartition()可以再t最右边部分进行分区
>>>s = "asd/fgh";
>>>s.partition("/")
('asd', '/', 'fgh')
s.replace(t, u, n) #返回s的一个副本,其中每个(或最多n个,如果给定)字符串t使用u替换
s.splitlines(f) #返回在行终结符处进行分割产生的行列表,并剥离行终结符(除非f为true)
s.strip(chars) #返回s的一个副本,并将开始处与结尾处的空白字符(或字符串chars中的字符)移除。s.rstrip()移除结尾,s.lstrip()移除开始
>>>"<[unbracketed]>".strip("[](){}<>");
'unbracketed'
s.swapcase() #返回s的副本,并将其中大写字符变为小写,小写字符变为大写
s.title() #返回s的副本,并将每个单词的首字母变为大写,其他字母都变为小写
s.zfill(w) #返回s的副本,如果比w短,就在开始处添加0,使其长度为w
s.maketrans() #创建字符间映射的转换表
s.translate() #转换表作为一个参数,并返回某个字符串根据该转换表进行转换后的副本
>>>table = "".maketrans("\N{bengali digit zero}"
"\N{bengali digit one}\N{bengali digit two}"
"\N{bengali digit three}\N{bengali digit four}"
"\N{bengali digit five}\N{bengali digit six}"
"\N{bengali digit seven}\N{bengali digit eight}"
"\N{bengali digit nine}", "0123456789")
>>>print("20749".translate(table)) #prints:20749
>>>print("\N{bengali digit two}07\N{bengali digit four}"
"\N{bengali digit nine}".translate(table)) #prints:20749
格式规约
#冒号(:)
>>>"{0:25}".format(s);
'The sword of truth'
#对齐字符(<左对齐,^中间对齐,>右对齐)
>>>"{0:>25}".format(s);
' The sword of truth'
>>>"{0:^25}".format(s);
' The sword of truth '
#破折号(-)
>>>"{0:-^25}".format(s);
'---The sword of truth----'
#点号(.)
>>>"{0:.<25}".format(s);
'The sword of truth.......'
>>>"{0:.10}".format(s);
'The sword'
#等于号(=)用于符号和数字之间
>>>"{0:0 = 12}".format(8749203);
'000008749203'
>>>"{0:0 = 12}".format(-8749203);
'-00008749203'
>>>"{0:012}".format(8749203);
'000008749203'
>>>"{0:012}".format(-8749203);
'-00008749203'
#展示符号
>>>"[{0: }][{1:}]".format(539802, -539802);
'[ 539802][-539802]'
>>>"[{0:+}][{1:+}]".format(539802, -539802);
'[+539802][-539802]'
>>>"[{0:-}][{1:-}]".format(539802, -539802);
'[539802][-539802]'
#进制符号(b二进制,o八进制,x十六进制)
>>>"{0:b} {0:o} {0:x} {0:X}".format(10);
'1010 12 a A'
#符号#
>>>"{0:#b} {0:#o} {0:#x} {0:#X}".format(10);
'0b1010 0012 0xa 0XA'
#逗号(,)
>>>"{0:,} {0:*>13,}".format(int(2.39432185e6));
'2,394,321 ****2,394,321'
locale模块
>>>import locale;
>>>locale.setlocale(locale.LC_ALL, '''');
>>>x, y = (123456789, 1234.56);
>>>locale.setlocale(locale.LC_ALL, "C");
>>>"{0:n} {1:n}".format(x, y); #'1234567890 1234.56'
>>>locale.setlocale(locale.LC_ALL, "en_US.UTF-8");
>>>"{0:n} {1:n}".format(x, y); #'1,234,567,890 1,234.56'
>>>locale.setlocale(locale.LC_ALL, "de_DE.UTF-8")
>>>"{0:n} {1:n}".format(x, y); #'1.234.567.890 1.234,56'
指数形式与标准形式
>>>amount = (10 ** 3) * math.pi;
>>>"[{0:12.2e}][(0:12.2f)]".format(amount); #e—使用小写字母e的指数形式,E—使用大写字母E的指数形式
'[ 3.14e+03][ 3141.59]' #
>>>"[{0:*>12.2e}][{0:*>12.2f}]".format(amount);
'[****3.14e+03][*****3141.59]'
>>>"[{0:*>+12.2e}][(0:*>+12.2f)]".format(amount);
'[***+3.14e+03][****+3141.59]'