简体   繁体   English

给定一个字符串 S,将其偶数索引字符和奇数索引字符作为 2 个空格分隔的字符串打印在一行中

[英]Given a string, S , print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line

I know it can be simply done through string slicing but i want to know where is my logic or code is going wrong.我知道这可以简单地通过字符串切片来完成,但我想知道我的逻辑或代码哪里出了问题。 Please Help!请帮忙!

S=input()
string=""
string2=""
list1=[]
list1[:0]=S
for i in list1:
    if(i%2==0):
        string=string+list1[i]
    else:
        string2=string2+list1[i]
print(string," ",string2)

Here's my code.这是我的代码。 Firstly i stored each character of string in the list and went by accessing the odd even index of the list.首先,我将字符串的每个字符存储在列表中,然后访问列表的奇偶索引。 But i'm getting this error但是我收到了这个错误

if(i%2==0):
TypeError: not all arguments converted during string formatting

You are iterating over characters, not indices, so your modulo is incorrect, equivalent to:您正在遍历字符,而不是索引,因此您的模数不正确,相当于:

i = "a"
"a" % 2 == 0

You want to use enumerate你想使用枚举

for idx, letter in enumerate(list1):
    if(idx%2 == 0)
         string += letter

You don't need to use an intermediate list: just iterate over the input string directly.您不需要使用中间列表:只需直接遍历输入字符串即可。 You also need to use for i in range(len(original)) rather than for i in original , because you need to keep track of whether a given character is at an odd or an even index.您还需要使用for i in range(len(original))而不是for i in original ,因为您需要跟踪给定字符是奇数索引还是偶数索引。 (I've gone ahead and renamed some of the variables for readability.) (为了便于阅读,我已经重命名了一些变量。)

S = input()
even_index_characters = ""
odd_index_characters = ""

for i in range(len(S)):
    if i % 2 == 0:
        even_index_characters += S[i]
    else:
        odd_index_characters += S[i]

print(f"{even_index_characters} {odd_index_characters}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 给定一个 string,将其偶数索引和奇数索引字符作为空格分隔的字符串打印在一行上 - Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line 如何打印字符串的偶数索引和奇数索引字符? - How to print the even-indexed and odd-indexed characters of strings? 对于每个 String S,打印 的偶数索引字符,后跟一个空格,然后是 的奇数索引字符 - For each String S, print 's even-indexed characters, followed by a space, followed by 's odd-indexed characters Pythonic方法将字符串列表转换为字典,奇数索引字符串作为键,偶数索引字符串作为值? - Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values? 替换字符串中的奇数和偶数索引字符 - Replacing Odd and Even-indexed characters in a string 将数组的偶数索引元素乘以 2,将数组的奇数索引元素乘以 3 - Multiply even-indexed elements of array by 2 and odd-indexed elements of array by 3 尝试从字符串中打印偶数索引字符 - Trying to print the even indexed characters from a string 将字符串列表转换为以空格分隔的字符串 - Convert list of strings to space-separated string 从 Python 中的列表中删除奇数索引元素 - Remove odd-indexed elements from list in Python 如何在列表中找到奇数索引值的乘积 - How to find the product of the odd-indexed values in a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM