华为机考入门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)
相关推荐
qq_356196952 分钟前
day47_预训练模型与迁移学习@浙大疏锦行
python
Tipriest_9 分钟前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法
老歌老听老掉牙26 分钟前
符号计算中的表达式等价性验证:数学等价性与计算简化策略分析
python·数学建模·sympy
scan72432 分钟前
向量数据库检索
python
摸鱼仙人~1 小时前
一文详解PyTorch DDP
人工智能·pytorch·python
超级种码1 小时前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
Salt_07282 小时前
DAY44 简单 CNN
python·深度学习·神经网络·算法·机器学习·计算机视觉·cnn
Iridescent11212 小时前
Iridescent:Day35
python
a程序小傲2 小时前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python
智航GIS3 小时前
2.3 运算符详解
开发语言·python