反转字符串中的每个单词 [英] Reverse each word in a string

查看:35
本文介绍了反转字符串中的每个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有一个小问题.我正在尝试反转字符串的单词和字符.例如狗跑"会变成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'

这篇关于反转字符串中的每个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆