2024-04-23 11:09:19 发布
网友
我已经做了一个程序,它可以反转给定的单词。事情是这样的:
word = input("Type text: ") x = len(word) y = x - 1 while y >= 0: print(word[y]) y -= 1
自然地,loop将每个字母打印在单独的行中,我不知道如何将这些字母组合成一个字符串。你能帮我吗
另一种方法是:
reversed = ''.join([word[len(word) - count] for count in range(1,len(word)+1)])
(对于Python 2,将范围替换为xrange)
将其存储在列表中,然后使用join。像这样:
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的步骤逐步遍历字符串
word[::-1]
另一种方法是:
(对于Python 2,将范围替换为xrange)
将其存储在列表中,然后使用
join
。像这样:使用
word[::-1]
反转字符串。这使用python的列表切片方法以-1的步骤逐步遍历字符串相关问题 更多 >
编程相关推荐