Python学习的第十天
评价算法好坏的标准:渐近时间复杂度和渐近空间复杂度
渐近时间复杂度通过O标记
os代表操作系统
os.windows(‘clear’) 用于清除输出
time.sleep() 用于让程序休眠
字符串
字符串的运算
- 拼接 +
contents = [
'请不要相信我的美丽',
'更不要相信我的爱情',
'因为在涂满油彩的面孔下',
'有着一颗戏子的心'
]
# 将列表中的元素用指定的字符串连接起来
print(' '.join(contents))
-
重复 *
-
成员运算in/not in
-
比较 从首位到末位按照字符的编码大小进行比较(不清楚对应编码可以通过ord()获得)
-
索引和切片除了不可以修改字符串中的字符,其他用法与列表相同
-
大小写转换
s1 = 'hello, world!'
# 使用capitalize方法获得字符串首字母大写后的字符串
print(s1.capitalize()) # Hello, world!
# 使用title方法获得字符串每个单词首字母大写后的字符串
print(s1.title()) # Hello, World!
# 使用upper方法获得字符串大写后的字符串
print(s1.upper()) # HELLO, WORLD!
s2 = 'GOODBYE'
# 使用lower方法获得字符串小写后的字符串
print(s2.lower()) # goodbye
- 查找
s = 'hello, world!'
# find方法从字符串中查找另一个字符串所在的位置
# 找到了返回字符串中另一个字符串首字符的索引
print(s.find('or')) # 8
# 找不到返回-1
print(s.find('shit')) # -1
# index方法与find方法类似
# 找到了返回字符串中另一个字符串首字符的索引
print(s.index('or')) # 8
# 找不到引发异常
print(s.index('shit')) # ValueError: substring not found
s = 'hello good world!'
# 从前向后查找字符o出现的位置(相当于第一次出现)
print(s.find('o')) # 4
# 从索引为5的位置开始查找字符o出现的位置
print(s.find('o', 5)) # 7
# 从后向前查找字符o出现的位置(相当于最后一次出现)
print(s.rfind('o')) # 12
- 性质判断
s1 = 'hello, world!'
# startwith方法检查字符串是否以指定的字符串开头返回布尔值
print(s1.startswith('He'))
# Falseprint(s1.startswith('hel')) # True
# endswith方法检查字符串是否以指定的字符串结尾返回布尔值
print(s1.endswith('!')) # True
s2 = 'abc123456'
# isdigit方法检查字符串是否由数字构成返回布尔值
print(s2.isdigit()) # False
# isalpha方法检查字符串是否以字母构成返回布尔值
print(s2.isalpha()) # False
# isalnum方法检查字符串是否以数字和字母构成返回布尔值
print(s2.isalnum()) # True
-
格式化字符串
s = 'hello, world' # center方法以宽度20将字符串居中并在两侧填充* print(s.center(20, '*')) # ****hello, world**** # rjust方法以宽度20将字符串右对齐并在左侧填充空格 print(s.rjust(20)) # hello, world # ljust方法以宽度20将字符串左对齐并在右侧填充~ print(s.ljust(20, '~')) # hello, world~~~~~~~~
变量值 占位符 格式化结果 说明 3.1415926
{:.2f}
'3.14'
保留小数点后两位 3.1415926
{:+.2f}
'+3.14'
带符号保留小数点后两位 -1
{:+.2f}
'-1.00'
带符号保留小数点后两位 3.1415926
{:.0f}
'3'
不带小数 123
{:0>10d}
0000000123
左边补 0
,补够10位123
{:x<10d}
123xxxxxxx
右边补 x
,补够10位123
{:>10d}
' 123'
左边补空格,补够10位 123
{:<10d}
'123 '
右边补空格,补够10位 123456789
{:,}
'123,456,789'
逗号分隔格式 0.123
{:.2%}
'12.30%'
百分比格式 123456789
{:.2e}
'1.23e+08'
科学计数法格式 -
通过字符串进行拆分
content = 'You go your way, I will go mine.'
content2 = content.replace(',', '').replace('.', '')
# 用空格拆分字符串得到一个列表
words = content2.split()
print(words, len(words))
for word in words:
print(word)
# 用空格拆分字符串,最多允许拆分3次
words = content2.split(' ', maxsplit=3)
print(words, len(words))
# 从右向左进行字符串拆分,做多允许拆分3次
words = content2.rsplit(' ', maxsplit=3)
print(words, len(words))
# 用逗号拆分字符串
items = content.split(',')
for item in items:
print(item)