我正在尝试做这个挑战,它给了我一个字符串,例如'Python'
,我需要删除每个第三个字符,或者每个字符哪个索引可以被3整除。在这个例子中,输出为yton
。到目前为止,我有word[::3]
部分找到每个第3个字符,但我如何从字符串中删除它们?
word = str(input())
newWord = word[::3]
print(newWord) #for testing
答案 0 :(得分:2)
输入字符串是不可变的,但将其转换为列表,您可以对其进行编辑:
>>> word = list(input()) # Read in a word
abcdefghijklmnop
>>> del word[::3] # delete every third character
>>> ''.join(word) # join the characters together for the result
'bcefhiklno'
从另一个角色开始:
>>> word = list(input())
123123123123
>>> del word[2::3]
>>> ''.join(word)
'12121212'
答案 1 :(得分:1)
检查出来:
>>> word = 'Python For All'
>>> new_word = ''.join(character for index, character in enumerate(word) if index%3 != 0)
>>> new_word
'ytonFo Al'