我现在的代码
sentence = "Sentence!"
print(*sentence[::3], sep="--")
输出:S--t--c
我如何反转切片,以便相同的输入将导致-en-en-e!
我尝试在::3
中使用-3和不同的数字,但无用
喜欢这个:
sentence = 'Sentence!'
import re
tokens = re.findall(r'.(..)', sentence)
print('', '-'.join(tokens), sep='-') # prints: -en-en-e!
编辑:在评论中解决问题:
This works, although how can I get this to start on the 3rd letter?
您可以尝试以下方法:
tokens = re.findall(r'(..).?', sentence[2:])
print('-'.join(tokens), sep='-')
这将输出:nt-nc
这是您想要的吗?
您试图使用切片无法实现的目标,因为您要保留的索引(1、2、4、5、7、8)不是arithmetic progression。
由于目标是将每三个字符的第一个字符替换为-
符号,所以我能想到的最简单的解决方案是使用正则表达式:
>>> import re
>>> re.sub(".(.{0,2})", r"-\1", "Sentence!")
'-en-en-e!'
>>> re.sub(".(.{0,2})", r"-\1", "Hello, world!")
'-el-o,-wo-ld-'
{0,2}
表示即使最后一组没有三个字母,模式也将匹配。
如果您想真正地反转范围,则在该范围内获取索引not:
''.join(sentence[i] if i not in range(0, len(sentence), 3) else '-'
for i in range(len(sentence)))
输出
'-en-en-e!'
个人,我更喜欢正则表达式解决方案。
另一种尝试:
sentence = ("Sentence!")
print(''.join(ch if i % 3 else '-' for i, ch in enumerate(sentence)))
打印:
-en-en-e!
如果sentence='Hello, world!'
:
-el-o,-wo-ld-