字符串(str)
注:与元组类似,字符串是不可变的,即不能被修改
1. 通用操作
索引、切片、相乘、相加、成员资格审查、长度、最大最小值
2. 输出字符串
格式:print(str)
2.1 三引号
>>> print('''the first line
... Hello,
... World!
... the last line''')
the first line
Hello,
World!
the last line
2.2 原始字符串
>>> print(r'c:\program files\software\python')
c:\program files\software\python
>>> print(repr('Hello\nworld!'))
'Hello\nworld!'
# 有需要转义的情况
>>> print(r'I'm hungry')
SyntaxError: invalid syntax
>>> print(r'I\'m hungry')
I\'m hungry
# 前缀r引号转义不能以单个反斜杠结尾
>>> print(r"This is illegal\")
SyntaxError: EOL while scanning string literal
>>> print(r"This is illeagl""\\")
This is illeagl\
2.3 格式设置运算符(%)
>>> name1 = 'ymk'
>>> name2 = 'Mary'
>>> print('Hello, %s.My name is %s.' % (name1, name2))
Hello, ymk.My name is Mary.
2.4 模板字符串(模块string: 了解)
>>> from string import Template
>>> templ = Template('Hello, $who! $what enough for ya?')
>>> templ.substitute(who='Mars', what='Dusty')
'Hello, Mars! Dusty enough for ya?'
2.5 format方法(提倡)
2.5.1 字段名
# 索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段
>>> name = 'Bob'
>>> f'{name} is acitive.' # 简写格式
'Bob is acitive.'
>>> '{}\'s age is {} years old'.format('Bob', 12)
"Bob's age is 12 years old"
>>> "{2}, {0} and {1}".format('one', 'two', 'three') # 有索引
'three, one and two'
>>> "{name}, {}, {} has something to eat".format('Mike', 'Tom', name='Saray')
'Saray, Mike, Tom has something to eat'
2.5.2 转换标志
# 跟在叹号(!)后面的单个字符
>>> print("{name!r} {name!s} {name!a}".format(name='张三'))
'张三' 张三 '\u5f20\u4e09'
2.5.3 格式说明符
# 跟在冒号(:)后面的表达式
>>> "The number is {num:b}, {num:f}, {num}".format(num=12)
'The number is 1100, 12.000000, 12'
2.5.4 自定义分隔符和结束字符串
>>> print('hello world', 'Hello Python')
hello world Hello Python
>>> print('hello world', 'Hello Python', sep='**')
hello world**Hello Python
>>> print('hello world', 'Hello Python', end="-*-")
hello world Hello Python-*->>>
"""引申:输入
int: 转换为整数
float: 转换为浮点数
"""
>>> input("What's your age?")
What's your age?10
'10'
3. 方法
查阅:https://docs.python.org/3/library/index.html
4. 编码问题
4.1 不可变的bytes对象
b’hello’
4.2 可变的bytearray对象
4.3 编码与解码
编码(encode):字符串–>bytes
解码(decode):bytes–>字符串