字符串格式化的3种方式
def test_1():
1.格式化的方式
dog = 'dog'
str1 = 'This is a %s' % dog
str2 = 'This is {} {}'.format('a', dog)
str3 = f'This is a {dog}'
assert 'This is a dog' == str1, r'% format error'
assert 'This is a dog' == str2, '{} format error'
assert 'This is a dog' == str3, 'f-string format errorr'
填充零的方式
def test_2():
2.填充零的方式
price = 123
# 其实我就用这一种, 后面的仅供参考
assert '0123' == f'{price:0>4}', 'format 3 error'
assert '0123' == '%04d' % price, ' format 1 error'
assert '0123' == str(price).rjust(4, '0'), 'rjust error'
assert '0123' == str(price).zfill(4), 'zfill error'
assert '0123' == '{:0>4}'.format(str(price)), 'format 2 error'
find和rfind获取字符串索引
def test_4():
# 4 startswith,find
raw = 'hello world $1 $2'
b1 = raw.startswith('hello')
assert b1, 'startswith error'
i1 = raw.find('$')
i2 = raw.rfind('$')
assert 12 == i1, 'find error'
assert 15 == i2, 'rfind error'
replace和正则替换
def test_5():
# 查找并替换
raw = 'hello world hello 1'
str1 = raw.replace('hello', 'good', 1)
assert 'good world hello 1' == str1, 'replace error'
reg = re.compile(r'^hello')
str2 = reg.sub('good', raw)
assert 'good world hello 1' == str2, 'replace error'
reg = re.compile(r'hello')
str3 = reg.sub('good', raw, 1)
assert 'good world hello 1' == str3, 'replace error'
split和rsplit
def test_7():
# split
raw = 'I am from jingzhou'
a1 = raw.split(' ')
assert {'I', 'am', 'from', '', 'jingzhou'} == set(a1), 'split error'
# \s+ 正则表示用1个或者多个空格分割,所以am from之间的两个空格会当做1个分割符去分割
a2 = re.split(r'\s+', raw)
assert {'I', 'am', 'from', 'jingzhou'} == set(a2), 'split re error'
# 取最后一个值
a3 = raw.rsplit(' ', 1)[1]
assert 'jingzhou' == a3, 'rsplit error'
字符串转数字
def test_8():
# 数字 isdecimal 不可以汉字,isdigit 不可以汉字, isnumeric可以汉字
# 我会优先用isdecimal,因为比较干净
raw1 = '123'
raw2 = '五'
assert raw1.isdecimal() == raw1.isdigit(
) == raw1.isnumeric() == True, 'isdecimal error'
assert not raw2.isdecimal(), 'isdecimal error'
assert not raw2.isdigit(), 'isdigit error'
assert raw2.isnumeric(), 'isnumeric error'
isspace和join
def test_9():
# isspace
raw = ' '
assert raw.isspace(), 'isspace error'
def test_10():
# join
raw1 = ['a', 'b', 'c']
assert 'a:b:c' == ':'.join(raw1)
审核编辑:刘清
-
字符串
+关注
关注
1文章
579浏览量
20549 -
python
+关注
关注
56文章
4797浏览量
84787
发布评论请先 登录
相关推荐
评论