python-3.x - 反转给定的字符串
问题描述
我正在编写一个程序来打印给定字符串的反转。我能够编写函数来反转字符串,但不能像测试用例中给出的那样接受尽可能多的输入。
我尝试过使用“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 //(在单独的行中)
解决方案
如果要保存和打印多个字符串,则需要一个数据类型来执行此操作。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))
推荐阅读
- java - Jasper Reports - 在 excel 导出中将所有报告打印到一张纸上
- node.js - 即使使用 withCredential: true,axios 也无法发送带有请求的 cookie
- php - Laravel 5 不同日期格式的独特(数据库)验证
- gulp - 使用 gulpjs 复制文件
- java - 在 LinkedList 中获取地图对象的索引
- php - 如何将此 1540621628 转换为正确的日期?
- javascript - 带有键的javascript数组包含另一个使用php的对象数组
- python - 如何在 Django 表单中设置表单项顺序?
- php - 为什么我的变量在我的 SELECT 语句中不起作用
- scheduler - WSL(Windows Subsystem for Linux)如何设置CPU/核心?