python—字符串与正则表达式

发布于:2024-04-28 ⋅ 阅读:(20) ⋅ 点赞:(0)

1、编写程序,生成一个由15个不重复的大小写字母组成的列表。

(1)源代码:

import random

import string

list1 = []

while len(list1) <= 15:

    x = random.choice(string.ascii_letters)

    if x not in list1:

        list1.append(x)

print("15个不重复的大小写字母组成的列表为:",list1)

(2)运行结果截图 :

2、给定字符串“site sea suede sweet see kase sse ssee loses",匹配出所有以s开头,e结尾的单词

(1)源代码:

import re

x = 'site sea suede sweet see kase sse ssee loses'

z = re.findall(r's[^0-9]e',x)

print("所有以s开头,e结尾的单词为:",z)

(2)运行结果截图 :

3、生成15个包括10个字符的随机密码,密码中的字符只能由大小写字母,数字和特殊字符“@”“$”“#”“&”“_”"~"构成。

(1)源代码:

import random

import string

list1 = []

# 生成包含大小写字母,数字和指定符号的字符串

x = string.ascii_letters + string.digits + "@$#&_~"

# 为了生成10个字符串元素,执行10次循环

while len(list1) <= 14:

    # 生成字符作为元素,个数为十个的字符列表y

    y = [random.choice(x) for i in range(10)]

    list1.append(" ".join(y))

else:

    print("生成结束:开始输出列表。")

print("列表为:", list1)

print("列表元素个数为:", len(list1))

(2)运行结果截图 :

4、给定列表x=[“13915556234”, “13025621456”, “15325645124” , “15202362459”]检查列表中的元素是否为移动手机号码,这里移动手机号码的规则是: 手机号码共11位数字;以13开头,后面跟4,5,6,7,8,9中的某一个;或者以15开头,后面跟0,1,2,8,9中的某一个。

(1)源代码:

import re

x = ["13915556234", "13025621456", "15325645124", "15202362459"]

for i in x:

    if len(i) == 11 and (re.findall(r'^13[4-9]', i) or re.findall(r'^15[01289]', i)):

        print(i)

(2)运行结果截图 :