1、定义
字符指类字形单位或符号,包括字母、数字、运算符号、标点符号和其他符号,以及一些功能性符号。
字符串是用一对引号括起来的字符序列,引号可以是单引号(’),双引号(")或者三引号(’’’)。其中三引号内的字符串可以不用转义符而跨越多行。
示例:
#单引号
>>> 'I like python!'
'I like python!'
>>>
#双引号
>>> "I like python!"
'I like python!'
>>>
#三引号 可以直接敲回车键,会转为\n
>>> '''I like python,
I also like pl/sql!'''
'I like python,\nI also like pl/sql!'
>>>
##双引号,敲回车键报错
>>> "I like python,
SyntaxError: EOL while scanning string literal
>>>
##用print输出三引号的跨行字符串
>>> print('''I like python,
I also like pl/sql!''')
I like python,
I also like pl/sql!
>>>
>>> print("I like python,I also like pl/sql!")
I like python,I also like pl/sql!
>>>
#用print输出双引号的跨行字符串,需要添加\n回车符
>>> print("I like python,\nI also like pl/sql!")
I like python,
I also like pl/sql!
>>>
>>> "I like python,\nI also like pl/sql!"
'I like python,\nI also like pl/sql!'
##双引号中的字符可以包含单引号,不用转义
>>>> "I'm a boy!"
"I'm a boy!"
>>>
#单引号中的字符包含单引号时,需要转义
>>> 'I\'m a boy!'
"I'm a boy!"
>>>
2、创建字符串
2.1、使用引号(单引号、双引号、三引号)创建
>>> 'abc'
'abc'
>>> "abc"
'abc'
>>> '''abc
def'''
'abc\ndef'
>>>
2.2、使用内置函数str将对象转换为字符串
>>> str(1234)
'1234'
>>>
>>> str((1,2,3,5))
'(1, 2, 3, 5)'
>>>
>>> str([1,2,3,4])
'[1, 2, 3, 4]'
>>>
2.3、使用字符串方法 join
>>> '-'.join(('2020','02','23'))
'2020-02-23'
>>>
>>> ' '.join(['I','love','python!'])
'I love python!'
>>>
3、字符串操作:
3.1、序列的通用操作
字符串是序列类数据结构,所以序列的通用操作(索引,切片、相加、乘法、成员资格检查)都可以使用,但是元素赋值和切片赋值非法,因为字符串是不可变的。
>>> 'abc'[0]
'a'
>>>
>>> 'abc'[1:2]
'b'
>>>
>>> 'abc'[1:]
'bc'
>>>
>>> 'abc'+'def'
'abcdef'
>>>
>>> 'abc'*5
'abcabcabcabcabc'
>>>
>>> 'a' in 'abc'
True
>>>
>>> 'e' in 'abc'
False
>>>
3.2、字符串方法
3.2.1、查看字符串的方法
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
3.2.2、几个常用的方法
3.2.2.1、split
根据指定字符参数分割字符串为列表对象。
>>> s = "I like python!"
>>> s.split(' ')
['I', 'like', 'python!']
2.2.2.2、format
格式化输出字符串
##按顺序替换字符串中的{}
>>> "{},{} and {}".format("first","second","third")
'first,second and third'
>>>
##{}内的索引对应format参数中的参数索引
>>> "{0},{2} and {1}".format("first","second","third")
'first,third and second'
>>>
>>> "{3} {0} {2} {1} {3} {0}".format("be","not","or","to")
'to be or not to be'
>>>
##按{}内的名称替换参数,并且可以指定格式
>>> "{name} : {value:.2f}".format(value=3.1415,name="pi")
'pi : 3.14'
>>>
>>> e = "python"
##简写格式
>>> f"I like {e}"
'I like python'
##与上面的表达式等价
>>> "I like {e}".format(e=e)
'I like python'
>>>
3.2.2.3、join
以字符串连接可迭代对象(元素是字符串),创建一个新字符串。
>>> '-'.join(('2020','02','23'))
'2020-02-23'
>>>
>>> ' '.join(['I','love','python!'])
'I love python!'
>>>
3.2.2.4、islower
判断字符串是否小写,是则返回Ture,否则返回False
>>> 'abc'.islower()
True
>>>
>>> "Abc".islower()
False
>>>
3.2.2.5、lower
转换字符串为小写
>>> "ABcdEF".lower()
'abcdef'
>>>
3.2.2.6、isupper
判断字符串是否大写,是则返回Ture,否则返回False
>>> 'ABcd'.isupper()
False
>>>
>>> 'ABCD'.isupper()
True
>>>
3.2.2.7、upper
转换字符串为大写字符。
>>> 'Abcd123'.upper()
'ABCD123'
>>>
3.2.2.8、center
通过在两天填充字符来让字符串居中。默认填充字符是空格。
>>> path.center(20)
' c:\nowhere '
>>>
>>> path.center(20,'*')
'*****c:\nowhere******'
>>>
3.2.2.9、find
在字符串中查找子串,如果找到,则返回找到的首个子串第一个字符的索引,否则返回-1.
>>> s
'to be or not to be'
>>>
>>> s.find('be')
3
>>>
>>> s.find('t')
0
>>>
>>> s.find('ok')
-1
>>>
3.2.2.10、strip
去掉字符串左右两边的给定字符,默认字符是空格。
>>> s1
' to be or not to be '
>>>
>>>
>>> s1.strip()
'to be or not to be'
>>>
>>>
>>> s2 = '*'*3 + s + '*' * 2
>>>
>>> s2
'***to be or not to be**'
>>>
>>>
>>> s2.strip('*')
'to be or not to be'
>>>
4、几个相关函数
4.1、print
将值打印到流或标准输出,默认是标准输出。
>>> print("Hello,python!")
Hello,python!
>>>
>>> print("Hello,\npython")
Hello,
python
>>>
## 指定r可以打印原始字符串而不转义
>>> print(r"Hello,\npython")
Hello,\npython
>>>
## 打印原始字符串也可以使用转义符\
>>> print("Hello,\\npython")
Hello,\npython
>>>
## 打印输出不是自己想要的结果
>>> print('e:\nothing')
e:
othing
>>>
## 指定打印原始字符串
>>> print(r'e:\nothing')
e:\nothing
>>>
4.2、input
从标准输入读取字符串,后面的换行符会被删除。
如果给了提示字符串,会被打印到标准输出(不包含换行符),在读入字符串之前。
>>> input("Put your name:")
Put your name:老赵
'老赵'
>>>
>>> age = input("Put your age:")
Put your age:30
>>> age
'30'
##注意:读入的是字符串,和整数相加报错
>>> age + 5
Traceback (most recent call last):
File "<pyshell#301>", line 1, in <module>
age + 5
TypeError: can only concatenate str (not "int") to str
>>>
4.3、repr
返回对象的标准字符串表示。
>>> repr(97)
'97'
>>>
>>> repr([1,2,3])
'[1, 2, 3]'
>>>
>>> repr((4,5,6))
'(4, 5, 6)'
>>>
>>>
>>> path
'c:\nowhere'
>>>
>>> print(path)
c:
owhere
>>>
##打印字符串形式,注意有引号
>>> print(repr(path))
'c:\nowhere'
>>>
4.4、bytes
格式:bytes(string, encoding[, errors])
将字符串进行编码,并与指定方式处理错误。
>>> bytes("Hello",encoding='utf-8')
b'Hello'
>>>
>>> bytes("Hello,中国",encoding='utf-8')
b'Hello,\xe4\xb8\xad\xe5\x9b\xbd'
>>>
>>> bytes("Hello,中国",encoding='utf-32')
b'\xff\xfe\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00,\x00\x00\x00-N\x00\x00\xfdV\x00\x00'
>>>
>>> bytes("Hello,中国",encoding='ascii')
Traceback (most recent call last):
File "<pyshell#332>", line 1, in <module>
bytes("Hello,中国",encoding='ascii')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-7: ordinal not in range(128)
>>>
>>>
bytes("Hello,中国",encoding='ascii',errors='ignore')
b'Hello,'
>>>
>>>
>>> bytes("Hello,中国",encoding='ascii',errors='replace')
b'Hello,??'
>>>
>>> bytes("Hello,中国",encoding='ascii',errors='backslashreplace')
b'Hello,\\u4e2d\\u56fd'
>>>
>>> bytes("Hello,中国",encoding='ascii',errors='xmlcharrefreplace')
b'Hello,中国'
>>>
4.5、string.capwords
将字符串转换为词首大写。 与字符串方法title类似。title方法有时词首判断不准。
>>> s
'to be or not to be'
>>> import string
>>> string.capwords(s)
'To Be Or Not To Be'
>>>
>>> s.title()
'To Be Or Not To Be'
>>>
##tital词首判断不准 's 中的s也大写了
>>> "that's ok!".title()
"That'S Ok!"
>>>
>>>
>>> string.capwords("that's ok!")
"That's Ok!"
>>>
5、设置字符串格式
5.1、%转换
%s 将值视为字符串进行格式设置。
%d 将值视为整数。
%.3f 将值视为包含3为小数的浮点数。
>>> 'pi is %.3f. a = %d. s = %s' % (3.1415,20,'hello')
'pi is 3.142. a = 20. s = hello'
>>>
5.2、模板字符串 : string.Template()
类似于shell语法。
>>> tmpl = tl('I like $lan1 and $lan2!')
>>> tmpl.substitute(lan1='python',lan2='pl/sql')
'I like python and pl/sql!'
>>>
5.3、字符串的format方法
目前最常用的设置格式方法。
5.3.1、替换字段概述
替换字段用花括号({})括起来,替换字段包含以下部分,每个部分都是可选的:
- 字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。
- 转换标志:跟在叹号后面的单个字符,当前支持的字符包括r(表示repr),s(表示str),a(表示ascii)
- 格式说明符:跟在冒号后的表达式。可以指定格式类型(如字符串、浮点数或十六进制数),字段宽度和数的精度,如何显示符号和千位分隔符,以及各种对其和填充方式。
5.3.2、示例
5.3.2.1、替换字段名
##通过字段名称与参数匹配
>>> "{foo} {bar}".format(bar="wu",foo="zhao")
'zhao wu'
>>>
##未命名字段名,按顺序将字段和参数配对
>>> "{} {}".format("zhang","san")
'zhang san'
>>>
##通过字段索引与参数进行匹配
>>> "{1} {0}".format("si",'li')
'li si'
>>>
>>> fullname = ['wang','wu']
##通过字段名称访问参数值得组成部分
>>> "Mr {name[0]}".format(name=fullname)
'Mr wang'
>>>
>>> import math
>>>
>>> tmpl = "The {mod.__name__} module defines the value {mod.pi} for π"
>>>
>>> tmpl.format(mod=math)
'The math module defines the value 3.141592653589793 for π'
>>>
5.3.2.2、基本转换
转换标识:叹号(!)
字符串格式设置中得类型说明符:
- b 将整数表示为二进制数
- c 将整数解读为Unicode码点
- d 将整数视为十进制数进行处理,这是整数默认使用的说明符
- e 使用科学表示法来表示小数(用 e 来表示指数)
- E 与 e 相同,但使用 E 来表示指数
- f 将小数表示为定点数
- F 与 f 相同,但对于特殊值( nan 和 inf ),使用大写表示
- g 自动在定点表示法和科学表示法之间做出选择。这是默认用于小数的说明符,但在默认情况下至少有1位小数
- G 与 g 相同,但使用大写来表示指数和特殊值
- n 与 g 相同,但插入随区域而异的数字分隔符
- o 将整数表示为八进制数
- s 保持字符串的格式不变,这是默认用于字符串的说明符
- x 将整数表示为十六进制数并使用小写字母
- X 与 x 相同,但使用大写字母
- % 将数表示为百分比值(乘以100,按说明符 f 设置格式,再在后面加上%)
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0'
>>>
>>> "The number is {num}".format(num=42)
'The number is 42'
>>>
##设置浮点数的格式时,默认在小数点后面显示6位小数。
>>> "The number is {num:f}".format(num=42)
'The number is 42.000000'
>>>
>>> "The number is {num:b}".format(num=42)
'The number is 101010'
>>>
5.3.2.3、宽度、精度和千位分隔符
宽度和精度用整数指定,指定精度时整数前要加点(.),千位分隔符用逗号(,)指定。
##指定宽度
>>> '{num:10}'.format(num=4)
' 4'
>>>
>>> "{num:10}".format(num='zhao')
'zhao '
>>>
>>>
>>> import math
>>>
>>> pi
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
pi
NameError: name 'pi' is not defined
>>>
>>>
>>> from math import pi
>>>
>>> pi
3.141592653589793
>>>
>>>
##指定精度
>>> "Pi = {pi:.2f}".format(pi=pi)
'Pi = 3.14'
>>>
>>> "Pi = {pi:10.2f}".format(pi=pi)
'Pi = 3.14'
>>>
>>> "Pi = {pi:5.2f}".format(pi=pi)
'Pi = 3.14'
>>>
##指定千位分隔符
>>> "One googol is{:,}".format(10**100)
'One googol is10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'
>>>
>>> "Num={:10,.3}".format(123456.345353535)
'Num= 1.23e+05'
>>>
>>> "Num={:20,.3}".format(123456.345353535)
'Num= 1.23e+05'
>>> "Num={:20,.3}".format(1234.345353535)
'Num= 1.23e+03'
>>>
##同时指定宽度,精度和千位分隔符
>>> "Num={:20,.3f}".format(1234.345353535)
'Num= 1,234.345'
>>>
>>> "Num={:20,.3f}".format(123456.345353535)
'Num= 123,456.345'
>>>
5.3.2.3、符号、对齐和用0填充
在指定精度和宽度的数之前,可添加一个标志。这个标志可以是零,加号,减号或空格,其中零表示用零来填充。
左对齐,右对齐和居中分别用<,>和^来指定。
说明符 = 指定将填充字符放在符号和数字之间。
说明符 + 指定给正数加上符号
说明符 空格 指定在正数前加上空格,而不是+
说明符 # 对于二进制,八进制,十六进制将加上一个前缀,对于十进制,它要求必须包含小数点。
>>>
>>>
##指定用0填充
>>> '{:010.2f}'.format(pi)
'0000003.14'
>>>
>>>
##左对齐,右对齐,居中对齐
>>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14
3.14
3.14
>>>
#指定用$填充
>>> "{:$^15}".format(" WIN BIG ")
'$$ WIN BIG $$'
>>>
>>> print('{0:10.2f}\n{1:10.2f}'.format(pi,-pi))
3.14
-3.14
>>>
## 说明符=指定将填充符放在符号和数字中间
>>> print('{0:10.2f}\n{1:=10.2f}'.format(pi,-pi))
3.14
- 3.14
>>>
##默认说明符 - ,正数前没有符号
>>> print('{0:-10.2f}\n{1:-10.2f}'.format(pi,-pi))
3.14
-3.14
>>>
##说明符 + 指定在正数前加符号
>>> print('{0:+10.2f}\n{1:+10.2f}'.format(pi,-pi))
+3.14
-3.14
>>>
##说明符空格,正数前加空格
>>> print('{0: 10.2f}\n{1: 10.2f}'.format(pi,-pi))
3.14
-3.14
>>>
>>> "{:b}".format(32)
'100000'
>>>
##说明符#在二进制、八进制、十六进制加前缀
>>> "{:#b}".format(32)
'0b100000'
>>>
>>> "{:#o}".format(32)
'0o40'
>>>
>>> "{:#x}".format(32)
'0x20'
##说明符#对十进制必须保留小数
>>> "{:#g}".format(32)
'32.0000'
>>>
>>> "{:g}".format(32)
'32'
>>>