华为机考入门python3--(31)牛客31-单词倒排

分类:字符串、正则

知识点:

  1. 正则提取所有符合的字符串 words = re.findall(r'[a-zA-Z]+', sentence)

  2. 列表倒序 words[::-1]

题目来自【牛客】

python 复制代码
import re  # 导入正则表达式模块

def reverse_words(sentence):
    # 使用正则表达式将句子拆分成单词
    # 如可以将$bo*y gi!r#l提取为['bo', 'y', 'gi', 'r', 'l']
    words = re.findall(r'[a-zA-Z]+', sentence)
    # print(words)
    
    # 对单词列表进行倒序,并用空格连接单词
    reversed_sentence = ' '.join(words[::-1])
    
    return reversed_sentence

# 输入
input_sentence = input()

# 倒排单词并输出结果
result = reverse_words(input_sentence)
print(result)
相关推荐
程序员爱钓鱼5 分钟前
Python 编程实战 · 进阶与职业发展:数据分析与 AI(Pandas、NumPy、Scikit-learn)
后端·python·trae
软件开发技术深度爱好者10 分钟前
Python库/包/模块管理工具
开发语言·python
程序员爱钓鱼18 分钟前
Python 编程实战 · 进阶与职业发展:Web 全栈(Django / FastAPI)
后端·python·trae
郝学胜-神的一滴1 小时前
Python中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
烤汉堡1 小时前
Python入门到实战:post请求和响应
python·html
夫唯不争,故无尤也2 小时前
Python广播机制:张量的影分身术
开发语言·python
流浪猪头拯救地球2 小时前
利用 Python 解密 / 加密 PDF 文件
python·pdf·php
花开花富贵2 小时前
多语言的爱意告白
python
百锦再3 小时前
第21章 构建命令行工具
android·java·图像处理·python·计算机视觉·rust·django
蒋星熠3 小时前
常见反爬策略与破解反爬方法:爬虫工程师的攻防实战指南
开发语言·人工智能·爬虫·python·网络安全·网络爬虫