Skip to main content
 首页 » 编程设计

python之我怎样才能反转切片

2025年05月04日11JustinYoung

我现在的代码

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(*tokens, sep='-') 

这将输出:nt-nc

这是你想要的吗?