我需要这样的东西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)
但这在传递上述示例输入时给了我不同的输出。逻辑也正确,那么错误在哪里?每当遇到空格时,我都必须跳到下一个字符。请帮助我,因为我是新手
简单的字符串切片,预先替换:
>>> s = "An apple a day keeps the doctor away"
>>> s.replace(" ", "")[::2]
'Aapedyepteotrwy'
您可以删除手前的空间,而不是在 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