![](/img/trans.png)
[英]Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line
[英]Given a string, S , print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line
我知道這可以簡單地通過字符串切片來完成,但我想知道我的邏輯或代碼哪里出了問題。 請幫忙!
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)
這是我的代碼。 首先,我將字符串的每個字符存儲在列表中,然后訪問列表的奇偶索引。 但是我收到了這個錯誤
if(i%2==0):
TypeError: not all arguments converted during string formatting
您正在遍歷字符,而不是索引,因此您的模數不正確,相當於:
i = "a"
"a" % 2 == 0
你想使用枚舉
for idx, letter in enumerate(list1):
if(idx%2 == 0)
string += letter
您不需要使用中間列表:只需直接遍歷輸入字符串即可。 您還需要使用for i in range(len(original))
而不是for i in original
,因為您需要跟蹤給定字符是奇數索引還是偶數索引。 (為了便於閱讀,我已經重命名了一些變量。)
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.