反转字符串中的每个单词

编程入门 行业动态 更新时间:2024-10-10 03:22:32
本文介绍了反转字符串中的每个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的代码有一个小问题.我正在尝试反转字符串的单词和字符.例如狗跑"会变成ehT God nar"

代码几乎可以工作.它只是不添加空格.你会怎么做?

def reverseEachWord(str):反向词=""列表=str.split()对于列表中的单词:字=字[::-1]反向词=反向词+词+"返回反向词

解决方案

您走对了.主要问题是 "" 是一个空字符串,而不是一个空格(即使你解决了这个问题,你可能也不希望在最后一个单词后面有一个空格).

以下是您可以更简洁地执行此操作的方法:

>>>s='狗跑了'>>>' '.join(w[::-1] for w in s.split())'ehT God nar'

I am having a small problem in my code. I am trying to reverse the words and the character of a string. For example "the dog ran" would become "ehT god nar"

The code almost works. It just does not add spaces. How would you do that?

def reverseEachWord(str): reverseWord="" list=str.split() for word in list: word=word[::-1] reverseWord=reverseWord+word+"" return reverseWord

解决方案

You are on the right track. The main issue is that "" is an empty string, not a space (and even if you fix this, you probably don't want a space after the final word).

Here is how you can do this more concisely:

>>> s='The dog ran' >>> ' '.join(w[::-1] for w in s.split()) 'ehT god nar'

更多推荐

反转字符串中的每个单词

本文发布于:2023-11-30 12:32:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   单词

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!