我需要这样的东西
accepted_string: An apple a day keeps the doctor away
resultant_string: Aapedyepteotrwy
为此,我写了这段代码:
accepted_string = input("enter")
add = ''
for count in range(0, len(accepted_string), 2):
if accepted_string[count] == " ":
count += 1
add = add + accepted_string[count]
else:
add = add + accepted_string[count]
print(add)
但是在传递上面的示例输入时,这给了我不同的输出。逻辑也正确,那么错误在哪里?每当遇到空白时,我都要跳到下一个角色。请帮助我,因为我是这个新手
答案 0 :(得分:2)
简单string slicing,之前为replacement:
>>> s = "An apple a day keeps the doctor away"
>>> s.replace(" ", "")[::2]
'Aapedyepteotrwy'
答案 1 :(得分:0)
你可以在手前删除空格而不是for for循环并使其列表转换为数组
<强>代码:强>
accepted_string = input("enter")
add = ''
accepted_string = list(accepted_string.replace(" ", ""))
print(accepted_string)
for count in range(0, len(accepted_string), 2):
add = add + accepted_string[count]
print(add)
<强>输出:强>
['A', 'n', 'a', 'p', 'p', 'l', 'e', 'a', 'd', 'a', 'y', 'k', 'e', 'e', 'p', 's', 't', 'h', 'e', 'd', 'o', 'c', 't', 'o', 'r', 'a', 'w', 'a', 'y']
Aapedyepteotrwy
第二段代码:
accepted_string = input("enter")
add = ''
char_count = 1
for count in range(0, len(accepted_string)):
if accepted_string[count] != " ":
char_count += 1
if char_count % 2 == 0:
add = add + accepted_string[count]
# add = add + accepted_string[count]
# else:
# add = add + accepted_string[count]
print(add)
<强>输出:强>
Aapedyepteotrwy