华为机考入门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)
相关推荐
程序员爱钓鱼1 小时前
Python编程实战 · 基础入门篇 | 元组(tuple)
后端·python·ipython
程序员爱钓鱼1 小时前
Python编程实战 · 基础入门篇 | 列表(list)
后端·python·ipython
御承扬3 小时前
编程素养提升之EffectivePython(Builder篇)
python·设计模式·1024程序员节
chenchihwen4 小时前
AI代码开发宝库系列:FAISS向量数据库
数据库·人工智能·python·faiss·1024程序员节
AI视觉网奇5 小时前
json 可视化 2025 coco json
python·1024程序员节
mit6.8246 小时前
[nanoGPT] ChatGPT 的 LLM 的全栈实现 | 快速上手
python
DKunYu6 小时前
2.1线性回归
pytorch·python·深度学习·1024程序员节
大飞记Python6 小时前
实战分享:一键自动化下载指定版本的Chrome及Chromedriver(附Python源码)
chrome·python·自动化
程序员杰哥7 小时前
如何使用Postman做接口自动化测试及完美的可视化报告?
自动化测试·软件测试·python·测试工具·jenkins·postman·1024程序员节
老歌老听老掉牙7 小时前
参数曲线切向量与叉乘向量的精确计算与分析
python·sympy·1024程序员节