python - 如何使用显式 "slice of s from i to j with step k"反转字符串?

标签 python string slice reverse indices

我已经看到了::-1可以用来反转字符串,但我认为找到显式整数 i:j:k 会很有趣。这样就可以完成这项工作。

我找到了文档common-sequence-operations ,但无法让它工作。此代码测试很简短:

s = "abcd"
print(1,s[4:3:-1]) 
print(2,s[4:2:-1])    
print(3,s[4:1:-1])
print(4,s[4:0:-1])
print(5,s[4:-1:-1])  

这是输出:

1 
2 d
3 dc
4 dcb
5 

看起来您无法使用明确的公式来做到这一点,s[i:j:k] .

通常我可以通过反复试验来找出简单的编程,但这在这里不起作用。也许仔细阅读文档会让我克服这个问题!

最佳答案

你必须这样做:

s = "abcd"
print(s[len(s):-len(s)-1:-1])

或者,正如 Terry Jan Reedy 所指出的那样在注释中,以下编写方式很好地说明了切片的长度:(stop - start)/step:

print(s[-1:-1-len(s):-1])

问题是负索引从后面开始,因此负索引对应于以下“真实”索引:

-1 ->  3
-2 ->  2
-3 ->  1
-4 ->  0  # -len(s)
-5 -> -1  # that's the one you need (or any smaller number)

0-len(s) 是不够的,因为切片的 stop 索引是独占的,因此您必须获取一个更低。

关于python - 如何使用显式 "slice of s from i to j with step k"反转字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307819/

相关文章:

c# - 在 C# 中安全地解析 XML

MySQL严格字符串比较语义上正确的方法?

python - TensorArray 和 while_loop 如何在 tensorflow 中协同工作?

python - 比较 2 个 Python 列表的顺序

python - 这个 SciPy 教程指的是什么 python 函数?

javascript - Array.slice 一个元素的数组

python - 从末尾开始迭代切片索引(python): how to avoid "-0" to be equal to "0"?

python - 无法在 Hadoop 中使用 python 运行 map reduce?

c++ - NTL 字符串到 ZZ 转换以及 ZZ 到字符串

go - 将uint32的字节附加到 byte slice 吗?