字符串
- 有序序列,至少可以是单字符 ‘c’, ‘ab’, “abc”,”’1234”’, “”“abcde”“”,
不可变,python3起字符串就是 Unicode type
- 定义字符串 s1=’string’ s2=”abc” s3=”“” comment”“”
- 字符串访问
sql = “select * from user where name=’tome’”
sql[4] - 有序
for c in sql:
print(c)
print(type(c)) - 可迭代
lst = list(sql)
字符操作
字符串连接
'string'.join(iterable) -> str
# iterable 要求本身元素是字符串 ','.join([1, 3, 5]) ','.join(['1','2'])
'a' + 'b' # 'ab'
list4 = ['1', ['a', 'b'], '3']
xx = '\n'.join(list4) # 参数 仅支持字符串可迭代对象
# TypeError: sequence item 1: expected str instance, list found
字符串分割
字符串分割分两类:
- split 将字符串按分割符分割为若干字符串,并返回列表 -> list
- partition 将字符串按分割符分割为 2 段,返回 2 段和分隔符的元组 -> tuple
# str.split(sep=None, maxsplit=-1) -> list of strings
s1 = "I'm \ta super studnet."
s1.split()
s1.split('', maxsplit=2)
# str.rsplit(sep=None, maxsplit=-1) -> list of strings
# str.splitlines([keepends]) -> list of strings
s1 = 'ab c\n\nde fg\rkl\r\n'.splitlines() # 按行来切分字符串
## partition
str.partition(sep) -> (head, sep, tail) # 如果没有找到分隔符,返回(head, '','') 的三元组
s1 = "I'm a super studnet"
s1.partition('s')
# str.rpartition(sep) -> (head, sep, tail) # 从右到左的顺序分割
字符串大小写
upper() # 全大写
lower()
swapcase() # 交换大小写
字符串排版
title() # 字符串中的单词首字母大写, 英语的标题化
capitalize() # 首个单词首字母大写
center(width, [fillchar]) -> str # fillchar 指定填充字符
zfill(width) -> str # 指定宽度,其他以 0 填充
ljust(width[, fillchar])
rjust(width[, fillchar])
字符串修改
字符串替换
replace(old, new[, count]) -> str
‘www.magedu.com’.replace(‘w’, ‘p’)
‘www.magedu.com’.replace(‘wwww’, ‘python’, 2)
字符串清洗
str.strip([chars]) -> str # 从字符串两端清洗指定的字符集 chars 中所有字符
str.lstrip([chars])
str.rstrip([chars])
字符串查找
- find 方法 找不到返回 -1
str.find(sub[, start[, end]]) -> int index
str.rfind(sub[, start[, end]]) -> int index
s = “I am very very very sorry”
s.find(‘very’, 6, 13)
s.find(‘very’, -10, -1)
s3[s3.find(‘very’):s3.find(‘very’) + len(‘very’)]
index 方法 找不到返回 ValueError
str.index(sub[, start[, end]]) -> int index
str.rindex(sub[, start[, end]]) -> int indexcount(sub[, start[, end]]) -> int 统计指定 sub出现次数
s.count(‘very’, 10, 14) # 可以指定区间
字符串查找总结:
- 时间复杂度 index/count 方法都是 O(n)
- len(string)
字符串判断
str.endswith(suffix[, start[, end]]) -> bool # 可以指定区间
str.startswith(prefix[, start[, end]]) -> bool # 可以指定区间
str.isalnum()
str.alpha()
str.isdecimal() # 是否只包含 十进制数字
str.isdigit() # 是否全部数字(0-9)
str.isidentifier() # 是否是标识符(字母,数字, 下划线)
str.islower()
str.isupper()
str.isspace() # 是否只包含空白字符
字符串格式化
- join 只能使用分隔符,且要求被拼接的是 可迭代字符串
-
- 要求非字符串需要先转换为字符串 str(s)
printf style 风格的print输出
- 使用占位符 format % values
# 占位符
%s str(s)
%d int(d) base 10
%o base 8
%x baee 16
%f float(f)
%n number
%e 科学计数法表示 e
# %修饰符占位符
m.n 显示最小宽度m,精度n
%-5d 左对齐
%+5d 正数前面显示 + 号
%#x base 8前显示 0o base 16前显示 0x64
'%s, %d, %#o, %#x, %#X %f' % (10, 10, 10, 10, 10, 10)
'10, 10, 0o12, 0xa, 0XA 10.000000'
str.format()方法
'{}:{}'.format('192.168.100.1', 8888)
'{0} love {1}.{2}'.format("I", "FishC", "com") # 位置参数
'{a} love {b}.{c}'.format(a="I", b="FishC", c="com") # 关键字参数
'{server} {1}:{0}'.format(8888, '192.168.1.1', server='Web Info:')
'{0[0]}.{0[1]}'.format(('magedu','com'))
from collections import namedtuple
Point = namedtuple('Point', 'x y')
p = Point(4, 5)
"{{{0.x}, {0.y}}}".format(p)
'{4, 5}'
使用format格式化字符串
‘{}’.format(values)
练习
用户输入一个数字
- 判断是几位数
- 打印每一位数字及其重复的次数
- 依次打印每一位数,顺序个, 十, 百, 千, 万
输入5个数字,打印每个数字的位数,将这些数字排序打印,要求升序打印
for i in range(length):
for j in range(length-i-1):
count += 1
if numsList[j] > numsList[j+1]:
tmp = numsList[j]
numsList[j] =numsList[j+1]
numsList[j+1] = tmp
count_swap += 1
print('sorted list: {0} swap: {1} count: {2}'.format(numsList, count_swap, count))