Python编程:re中findall()用法

        在re中,(re.findall(pattern, string, flags=0)):返回string中所有与pattern相匹配的全部字符串,得到数组。其用法大致分为四类,如下:

(1)r:查找string中出现r标识的字串

import re
text = "https://mp.csdn.net/postedit/82865219"
a = re.findall(r"pos", text)
#输出 
a = ['pos']

(2)^:匹配以^标识开头的字符串;$:匹配以$标识结束的字符串

import re
text1 = "https://mp.csdn.net  wwww "
text2 = "blog.csdn.net"
a1 = re.findall(r"^https", text1)
a2 = re.findall(r"^https", text2)
a3 = re.findall(r"$net", text1)
a4 = re.findall(r"$net", text2)
#输出 
a1 = ['https']
a2 = []
a3 = []
a4 = ['net']

(3)匹配括号中的其中一个字符

import re
text = "I am so happy! "
a1 = re.findall("[a-zA-Z]", text)
a2 = re.findall("[a-zA-Z]+", text)
 
#输出
a1 = ['I', 'a', 'm', 's', 'o', 'h', 'a', 'p', 'p', 'y']
a2 = ['I', 'am', 'so', 'happy']

(4)\d:匹配0到9之间的数字;\D:匹配除0到9之外的字符

import re
text = "https://mp.csdn.net/postedit/82865219"
a1 = re.findall("\d", text)
a2 = re.findall("\d\d", text)
a3 = re.findall("\D", text)
a4 = re.findall("\D+", text)
#输出 
a1 = ['8', '2', '8', '6', '5', '2', '1', '9']
a2 = ['82', '86', '52', '19']
a3 = ['h', 't', 't', 'p', 's', ':', '/', '/', 'm', 'p', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't', '/', 'p', 'o', 's', 't', 'e', 'd', 'i', 't', '/']
a4 = <class 'list'>: ['https://mp.csdn.net/postedit/']

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资料:青少年编程等级考试 - Python编程三级试卷5 1. 请问Python如何定义函数?函数的定义格式是怎样的? 在Python,我们可以使用关键字“def”来定义函数。函数的定义格式如下: def 函数名(参数列表): 函数体 2. Python如何判断一个数是否为质数? 判断一个数是否为质数可以使用循环判断的方法。我们可以使用for循环从2遍历到该数的平方根,如果能整除,则说明不是质数。 def is_prime(num): if num < 2: return False for i in range(2, int(num**0.5)+1): if num % i == 0: return False return True 3. 请问Python如何读取文本文件? Python可以使用open函数来打开文件,并且使用readlines方法来读取文本文件的内容。 def read_file(file_name): try: with open(file_name, 'r') as file: lines = file.readlines() for line in lines: print(line.strip()) # 使用strip方法去除换行符 except FileNotFoundError: print("文件未找到!") 4. 如何使用Python进行文件的写入操作? 使用Python进行文件写入操作,可以使用open函数来打开文件,并且使用write方法来进行写入。 def write_file(file_name, content): with open(file_name, 'w') as file: file.write(content) 5. 请问Python如何使用正则表达式进行匹配? 在Python,可以使用re模块来进行正则表达式的匹配操作。 import re pattern = r'\d+' # 匹配数字 text = 'Hello123World456' result = re.findall(pattern, text) print(result) # 输出['123', '456'] 以上就是关于资料《青少年编程等级考试 - Python编程三级试卷5》的解答。希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值