题目大意是从a-z,0-9里面,写一个方法随机选取3个字符组成一个新的字符串
我这里想到就是使用随机数来解决,大概过程如下:
先用random.sample设置一个随机数产生的范围,然后在选择需要从中选取几个数据。通过for循环得到里面的数据,转为str类型,最后再用join函数进行一个拼接
demo如下:
import random def random_demo(str_length): random_num = random.sample(['a','b','c','d','e','f','g','h','i','j','k','l''m','n',1,2,3,4,5,6,7,8,9],str_length) data = [str(i) for i in random_num] print(data) new_str = "".join(data) print(new_str) if __name__ == '__main__': random_demo(7)
运行结果:
统计字符串出现字符的个数:
str1 = "python world hello" newdict = {} for i in str1: newdict[i] = newdict.get(i,0)+1 print(newdict)
运行结果:
循环遍历列表,将逗号改为分号,最后一个不加分号:
cmds = ["ls -l","cd","find"] for i in range(len(cmds)): # print(cmds[i]) if i == len(cmds)-1: pass else: cmds[i] = cmds[i]+";" print(cmds[i])