格式化Python中的字符串切片所需的输出

时间:2019-05-22 18:49:28

标签: python-3.x

这里是python的入门者,我有一个代码,该代码应该均匀且奇特地分割字符串并显示它。

这是我的代码:

def even_bits(str):
    result = ""  
    for i in range(len(str)):
        if i % 2 == 0:
            result = result + str[i]
    return result
def odd_bits(str):
    result = ""  
    for i in range(len(str)):
        if i % 2 == 1:
            result = result + str[i]
    return result


for i in range(int(input())):
    w = input('')    
    print(even_bits(w), ' ' ,odd_bits(w))

这可以正常运行,但是输出如下:

Sample Input: 
2
Hello
World

Sample Output: 
2
Hello
Hlo el

World
Wrd ol

如何格式化输出,以便获得如下输出:

Sample Output:
Hlo el
Wrd ol

先谢谢您。

2 个答案:

答案 0 :(得分:1)

您可以首先声明一个包含所有输入字符串的输入列表。然后遍历输入列表并打印偶数和奇数字符:

def even_bits(chain):
    result = ""
    for i in range(len(chain)):
        if i % 2 == 0:
            result = result + chain[i]
    return result


def odd_bits(chain):
    result = ""
    for i in range(len(chain)):
        if i % 2 == 1:
            result = result + chain[i]
    return result


input_list = [] # input list that contains all input strings

for i in range(int(input())):
    w = input('')
    input_list.append(w)

# iterate over input list to print even and odd characters
for inp in input_list:
    print(even_bits(inp), ' ', odd_bits(inp))

答案 1 :(得分:0)

您可以列出两个结果列表。一个用于偶数输出,一个用于奇数输出,然后压缩它们并打印每个元素。此外,您可以使用单个切片轻松获取偶数和奇数字母。

x = "Hello world"
# slicing looks like [START:STOP:STEP], so we can do
evens = x[0::2] # Will start at 0, go to the end, and take every 2nd character
odds  = x[1::2] # Will start at 1, go to the end, and take every 2nd character
print(evens) # >>> Hlowrd
print(odds)  # >>> el ol

即使您有一个空字符串,它也可以工作。

将它们放在一起,看起来可能像这样:

def even_bits(my_str):
    return my_str[0::2]

def odd_bits(my_str):
    return my_str[1::2]

even_results = []
odd_results = []
for i in range(int(input("How many inputs: "))):
    w = input('Input # {}: '.format(i+1))    
    even_results.append(even_bits(w))
    odd_results.append(odd_bits(w))

for ev, od in zip(even_results, odd_results):
    print(ev, od)

输出:

How many inputs: 2
Input # 1: Hello
Input # 2: World
Hlo el
Wrd ol