我怎样才能反转字符串

2024-04-23 11:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经做了一个程序,它可以反转给定的单词。事情是这样的:

word = input("Type text: ")
x = len(word)
y = x - 1

while y >= 0:
   print(word[y])
   y -= 1

自然地,loop将每个字母打印在单独的行中,我不知道如何将这些字母组合成一个字符串。你能帮我吗


Tags: 字符串text程序loopinputlentype字母
3条回答

另一种方法是:

reversed = ''.join([word[len(word) - count] for count in range(1,len(word)+1)])

(对于Python 2,将范围替换为xrange)

将其存储在列表中,然后使用join。像这样:

word = input("Type text: ")
x = len(word)
y = x - 1
store_1 = []
while y >= 0:
   store_1.append(word[y])
   y -= 1
together = ''.join(store_1)
print(together)

使用word[::-1]反转字符串。这使用python的列表切片方法以-1的步骤逐步遍历字符串

相关问题 更多 >