【问题标题】:How to use slicing/slice notation in Python如何在 Python 中使用切片/切片表示法
【发布时间】:2020-02-07 20:04:48
【问题描述】:

所以我做了一个翻译器,它需要一个英文句子,将最后一个字母移到前面,在每个单词后添加 mu,然后在每三个单词后添加 emu。现在我想做相反的事情。我似乎无法超越现在将单词的第一个字母移到单词末尾的部分。这个堆栈溢出帖子How to move the first letter of a word to the end 给我的印象是,通过使用 word[1:] + word[0] 我可以做到这一点,但我试图实现它,但它似乎没有做任何事情。

这是我当前的代码:

sentence = 'imu odmu tnomu emu wknomu whomu otmu emu odmu sthimu'
#This is the result of the english translated sentence

#Get rid of mu and emu 
sentence = sentence.replace('mu', '')
sentence = sentence.replace('e ', '')

#I would like this to move the first letter of each word to the end
print("".join([words[1:] + words[0] for words in sentence]))

#Current output i od tno wkno who ot od sthi
#Expected Output i do not know how to do this

只是好奇是否有人可以帮助向我解释我在这里缺少什么

【问题讨论】:

  • for words in sentence 不产生单词;它产生单个字符。如果您想要文字,请使用for words in sentence.split()
  • 是啊,傻我忘了事先拆开它

标签: python python-3.x slice


【解决方案1】:

split() 将采用任何字符串并将其拆分为 list 在您在调用中使用的任何字符。默认是一个空格,所以你需要做的就是把句子分成单词,而不是对字符进行操作。

sentence = 'imu odmu tnomu emu wknomu whomu otmu emu odmu sthimu'
#This is the result of the english translated sentence

#Get rid of mu and emu 
sentence = sentence.replace('mu', '')
sentence = sentence.replace('e ', '')

#I would like this to move the first letter of each word to the end
print(" ".join([words[1:] + words[0] for words in sentence.split()]))
>>> i do not know how to do this

【讨论】:

  • 既然我的回答有效,我会很感激你接受它:)
  • 是的,我只需要再等几分钟
猜你喜欢
  • 2019-03-06
  • 2012-08-23
  • 2016-03-27
  • 1970-01-01
  • 2011-10-27
  • 2011-04-24
  • 2017-01-05
  • 2021-11-26
  • 1970-01-01
相关资源
最近更新 更多