其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

Python正则表达式

GG网络技术分享 2025-03-18 16:14 0


问题描述:

问题遇到的现象和发生背景

Cats are smarter than dogs.
这句话用正则表达式改变为 Dogs are smarter than cats. 注意大小写

问题相关代码,请勿粘贴截图

import re

text="Cats are smarter than dogs."
运行结果及报错内容
我的解答思路和尝试过的方法

先转换成小写,将首尾互换,再将首字母改成大写,但是不会写相关的正则表达式

我想要达到的结果

Cats are smarter than dogs.
这句话用正则表达式改变为 Dogs are smarter than cats. 注意大小写

网友观点:

这个意思?

import re

s = "Cats are smarter than dogs."

res = re.findall("^(.*?) (.*) (.*?)\\.$", s)[0]

s1 = f"{res[2].title()} {res[1]} {res[0].lower()}."

print(s1)

Python语言基础(7.8)re模块(正则表达式)

正则表达式是一种文本模式,用于搜索匹配文本中的一个或多个字符串。

Python 提供名为 re 的内置包,可用于处理正则表达式。

一、re 中的方法

1.match

匹配字符串的开始,如果匹配成功,则返回match对象。没有匹配,则返回none。

格式:match(<正则表达式>,<字符串>)

标签:

提交需求或反馈

Demand feedback