如何在python中打印一个没有三分之一字符的字符串?

2024-09-28 17:20:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试这个挑战,它给我一个字符串,比如'Python',我需要删除每三个字符,或者索引可以被3整除的每个字符。在本例中,输出将是yton。到目前为止,每三个字符都有word[::3]部分来查找,但是如何从字符串中删除它们呢?在

代码

word = str(input())
newWord = word[::3]
print(newWord) #for testing

Tags: 字符串代码forinput字符testingwordprint
3条回答

输入字符串是不可变的,但将其转换为列表,您可以对其进行编辑:

>>> 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'

从不同的字符开始:

^{pr2}$

看看这个:

>>> word = 'Python For All'
>>> new_word = ''.join(character for index, character in enumerate(word) if index%3 != 0)
>>> new_word
'ytonFo Al'

我的答案是:

s = '0123456'
print s[::3]
# 036

# first way(understandable) create a new str
s_new = ''
for i in xrange(len(s)):
    if i % 3 != 0:
        s_new += s[i]

print s_new
# 1245

# second way
s_lst = [c if i % 3 else '' for i, c in enumerate(s)]
print s_lst
# ['', '1', '2', '', '4', '5', '']
s_new = ''.join(s_lst)
print s_new
# 1245

# you can put it in single line
s_new = ''.join([c if i % 3 else '' for i, c in enumerate(s)])
print s_new
# 1245

# third way
s_idx = filter(lambda x: x[0] % 3, enumerate(s))
print s_idx
# [(1, '1'), (2, '2'), (4, '4'), (5, '5')]
print ''.join([x[1] for x in s_idx])
# 1245

相关问题 更多 >