华为机考入门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)
相关推荐
码农小卡拉4 小时前
Java多线程:CompletableFuture使用详解(超详细)
java·开发语言·spring boot·python·spring·spring cloud
Robot侠4 小时前
从 Python 到 Ollama:将微调后的 Llama-3/Qwen 一键导出为 GGUF
开发语言·python·llama·qwen
l1t4 小时前
Python 字符串反转方法
linux·开发语言·python
Eiceblue4 小时前
使用 Python 写入多类型数据至 Excel 文件
开发语言·python·excel
deephub4 小时前
Pydantic-DeepAgents:基于 Pydantic-AI 的轻量级生产级 Agent 框架
人工智能·python·深度学习·大语言模型·ai-agent
WarrenWu4 小时前
SQLAlchemy + Pytest:如何优雅地关闭异步数据库连接池
后端·python
写文章的大米4 小时前
性能提升5倍!Python列表和元组的底层原理揭秘
后端·python
坐吃山猪4 小时前
Google的A2A智能体群聊
python·llm·a2a
Lucky高5 小时前
Pandas库实践3_索引
开发语言·python·pandas
Iridescent11215 小时前
Iridescent:Day33
python