首页 > 解决方案 > 反转给定的字符串

问题描述

我正在编写一个程序来打印给定字符串的反转。我能够编写函数来反转字符串,但不能像测试用例中给出的那样接受尽可能多的输入。

我尝试过使用“while”循环,但我无法将所有测试用例作为输入。也许语法是错误的。我是新手。

def rev(sample_string):
    return sample_string[::-1]

t_case = int(input())   #No. of testcases
i = 0

while i < t_case:
    sample_string = str(input(""))    #take as many inputs as no. of 
                                      #testcases 
    i =+ 1

print(rev(sample_string))

样本输入:2、ab、aba -------- 输出应为:ba、aba //(在单独的行中)

标签: python-3.x

解决方案


如果要保存和打印多个字符串,则需要一个数据类型来执行此操作。List 会做这项工作:

def rev(sample_string):
    return sample_string[::-1]

t_case = int(input())   #No. of testcases
i = 0
string_list = []  # List to store the strings

while i < t_case:
    string_list.append(str(input("")))    #take as many inputs as no. of 
                                      #testcases 
    i += 1

for string in string_list:  # iterate over the list and print the reverse strings
    print(rev(string))

推荐阅读