Python 字符串测试

常用字符串方法如下:

- 获取长度:len

- 查找内容:find,index,rfind,rindex

- 判断:startswith,endswith,isalpha,isdigit,isalnum,isspace

- 计算出现次数:count

- 替换内容:replace

- 切割字符串:split,rsplit,splitlines,partition,rpartition

- 修改大小写:capitalize,title,upper,lower

- 空格处理:ljust,.rjust,center,Istrip,rstrip,strip

- 字符串拼接join

测试代码1:

结合random 创建随机组合的文件名,从一串字符串中随机去除4个字符组合成文件名

import random

# 字母和数字的组合

Filename =''

s ='QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjkLzxcvbnm1234567890'

for i in range(4):

    index = random.randint(0, len(s) -1)# 8

    Filename += s[index]

print(Filename)

输入:

Hs4y

测试2:

封装函数

def Get_randName():

Filename =''

    s ='QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjkLzxcvbnm1234567890'

    for i in range(4):

index = random.randint(0, len(s) -1)# 8

        Filename += s[index]

return Filename

创建一个列表,测试循环执行10次,创建10个随机名字

listName = []

for x in range(11):

    name = Get_randName()

    listName.append(name)

print(listName)

输出:

[‘t8JX’, ‘Idjn’, ‘8nuN’, ‘PToa’, ‘Qv7V’, ‘pnjT’, ‘emxo’, ‘HtZt’, ‘0PHn’, ‘cv7t’, ‘Q9T4’]

创建随机名称文件或文件夹。

你可能感兴趣的:(Python,Python,字符串,创建随机字符串)