华为机考入门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)
相关推荐
MurphyStar几秒前
Jupyter无法导入库,但能在终端导入的问题
python·jupyter
PeterClerk32 分钟前
基于Pygame的贪吃蛇小游戏实现
开发语言·python·pygame
Lightning-py40 分钟前
Python使用(...)连接字符串
开发语言·python
梅孔立1 小时前
linux 默认 python 2.7 版本没有pip安装教程
linux·python·pip
Jesse_Kyrie1 小时前
配置windows环境下独立浏览器爬虫方案【不依赖系统环境与chrome】
前端·chrome·爬虫·python·scrapy
pyniu1 小时前
研0学习Python基础4
开发语言·python
DZSpace1 小时前
Python脚本:将Word文档转换为Excel文件
python·word·excel
Wen.py.java1 小时前
Python商务数据分析知识专栏(五)——Python数据分析的应用③使用Pandas进行数据预处理
python·数据分析·pandas
白骑士所长1 小时前
白骑士的Python教学基础篇 1.5 数据结构
开发语言·python
网恋褙骗八万1 小时前
pytorch跑手写体实验
人工智能·pytorch·python