[英]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.