华为机考入门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)
相关推荐
chushiyunen7 分钟前
django使用笔记
笔记·python·django
2501_9411113429 分钟前
实战:用OpenCV和Python进行人脸识别
jvm·数据库·python
ada7_29 分钟前
LeetCode(python)——73.矩阵置零
python·算法·leetcode·矩阵
程序员爱钓鱼41 分钟前
Python编程实战:用好 pdb 和 logging,程序再也不黑箱运行了
后端·python·trae
程序员爱钓鱼42 分钟前
Python编程实战:从 timeit 到 cProfile,一次搞懂代码为什么慢
后端·python·trae
2501_941111511 小时前
Python多线程与多进程:如何选择?(GIL全局解释器锁详解)
jvm·数据库·python
2501_941111331 小时前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
小小测试开发1 小时前
Python数据科学与图像处理利器组合:Prophet、Arch、Scikit-image、Pillow-heif用法全解析
图像处理·python·pillow
2501_941111372 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
2501_941111344 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python