【问题标题】:Trying to split a string into a list, reverse the order of the list, and then print out a string of the reversed string试图将一个字符串拆分成一个列表,将列表的顺序颠倒,然后打印出颠倒后的字符串
【发布时间】:2019-01-01 01:52:33
【问题描述】:

我有一个字符串,我将其拆分为一个列表,并且能够以相反的顺序成功地正确打印出来。但是,当我将列表重新加入字符串时,它只是作为列表保留。我的加入功能哪里出错了?

我的代码:

sample_string = 'Hello Dragon and Snakie'

words = sample_string.split(" ")
reordered = str(words[::-1])
final = "".join(reordered)
print(final)

预期:蛇和龙你好

实际:['Snakie', 'and', 'Dragon', 'Hello']

谢谢

【问题讨论】:

  • 你的输出实际上是一个字符串——一个带括号的字符串,所以它看起来像一个列表。 reordered 是一个字符串,而不是一个列表。只需取出str 函数并为您的join 方法添加一个空格来分隔单词。

标签: python python-3.x


【解决方案1】:

替换这一行:

reordered = str(words[::-1])

与:

reordered = words[::-1]

因为你把列表变成了一个包含列表的字符串,所以它不会加入列表。

同时替换这一行:

final = "".join(reordered)

与:

final = " ".join(reordered)

因为你想加入空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2022-01-02
    • 1970-01-01
    • 2015-06-21
    相关资源
    最近更新 更多