python常规函数测试

python常规函数测试,第1张

python常规函数测试

文章目录

1. strip(),lstrip(),rstrip()2. split()3. readlines()& readline()4. most_common

1. strip(),lstrip(),rstrip()

作用:返回所给的字符串的副本,并删除前缀和后缀字符,如果函数给定的值为空(strip()),则删除特殊字符[’r’,’t’,’n’,空格],如果函数为strip(‘a’),则删除前缀和后缀中的字符 ‘a’

代码

a = " t zhang zh an g n"
# 空格+t+空格+zhang zh an g+空格+n
# 共 18 个字符,所以 a 的长度为 18
print(f'len(a)={len(a)}')
print(f'a={a}')
# strip函数的作用是消除字符串 前面和后面的特殊字符
# 这里的字符有的是 r,t,n,空格,字符串中间的字符不处理
a_strip = a.strip()
# 所以 a_strip 长度为 18-5=13
print(f'len(a_strip)={len(a_strip)}')
print(f'a_strip={a_strip}')
# 左边的特殊字符为 3 个
# 右边的特殊字符为 2 个
# a_lstrip = 18 - 3 = 15
# a_rstrip = 18 - 2 = 16
a_lstrip = a.lstrip()
print(f'len(a_lstrip)={len(a_lstrip)}')
print(f'a_lstrip={a_lstrip}')
a_rstrip = a.rstrip()
print(f'len(a_rstrip)={len(a_rstrip)}')
print(f'a_rstrip={a_rstrip}')

结果

len(a)=18
a= 	 zhang zh an g 

len(a_strip)=13
a_strip=zhang zh an g
len(a_lstrip)=15
a_lstrip=zhang zh an g 

len(a_rstrip)=16
a_rstrip= 	 zhang zh an g
2. split() 3. readlines()& readline()

readlines : 一次性读取每行数据,按行存储,返回一个 list 方便我们调用
readline :一次只读取一行,如果要读取第二行,只能重复此命令

代码
我们新建一个 test.txt文件
内容如下:

今天周六,出去玩了一圈
明天周日,明天一定要好好学习!
print('*'*100)
print('用 readlines 作为函数调用')
list = []
with open('test.txt', 'r') as f:
	ff = f.readlines()
	print(f'ff={ff}')
	for line in ff:
		line = line.strip()
		print(f'line={line}')
		list.append(line)
print(f'list={list}')

print('*'*100)
print('用 readline 作为函数调用')
list_line = []
with open('test.txt', 'r') as f:
	ff = f.readline()
	print(f'ff={ff}')
	for line in ff:
		line = line.strip()
		print(f'line={line}')
		list_line.append(line)
print(f'list={list_line}')

结果

****************************************************************************************************
用 readlines 作为函数调用
ff=['今天周六,出去玩了一圈n', '明天周日,明天一定要好好学习!']
line=今天周六,出去玩了一圈
line=明天周日,明天一定要好好学习!
list=['今天周六,出去玩了一圈', '明天周日,明天一定要好好学习!']
****************************************************************************************************
用 readline 作为函数调用
ff=今天周六,出去玩了一圈

line=今
line=天
line=周
line=六
line=,
line=出
line=去
line=玩
line=了
line=一
line=圈
line=
list=['今', '天', '周', '六', ',', '出', '去', '玩', '了', '一', '圈', '']
4. most_common

在collection库中有一个Counter类,可以统计字符串个数

代码

from collections import Counter

str = 'aaabbbbcccccddddddeeeeeeee'
user_counter = Counter(str)
# 统计字符串中字符数量最高的 3 个

common_most_user_counter = user_counter.most_common(3)
print(f'common_most_user_counter={common_most_user_counter}')

结果

common_most_user_counter=[('e', 8), ('d', 6), ('c', 5)]

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5701456.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存