简体   繁体   English

字符串切片返回意外值

[英]String slicing returning unexpected values

I hope this is a simple question!我希望这是一个简单的问题! I am trying to reverse a number, and be given the digits in the 'even' positions.我正在尝试反转一个数字,并在“偶数”位置给出数字。 When I try to do this within one string slice, I am just given a single digit, even when I am expecing more.当我尝试在一个字符串切片中执行此操作时,即使我期待更多,我也只得到一个数字。 When I do it as two slices, I am given the correct answer, but I am unsure why.当我把它分成两片时,我得到了正确的答案,但我不确定为什么。

For example, if I have the number 512341234, I would expect it to give me 3131, as I have first reversed the string (432143215) and then taken the even position numbers (4[3]2[1]4[3]2[1]5).例如,如果我有数字 512341234,我希望它给我 3131,因为我首先反转字符串 (432143215) 然后取偶数位置数字 (4[3]2[1]4[3]2 [1]5)。

Below is the code which I have tried to use to make it work, but doing it as one slice only returns the single digit, whereas doing it as two means it returns the expected value.下面是我试图用来使其工作的代码,但是将其作为一个切片仅返回一位数,而将其作为两个切片则意味着它返回预期值。 Why is this?为什么是这样?

num = 512341234
str(num)[1::-2] #returns 1
str(num)[::-1][1::2] #returns 3131

Thanks!谢谢! Noah诺亚

1::-2 means to start at position 1 (the second character) and go backwards two characters at a time. 1::-2表示从位置 1(第二个字符)开始,一次向后两个字符。 You want to start somewhere near the end of the string, eg您想从字符串末尾附近的某个地方开始,例如

num = 512341234
str(num)[-1::-2]
'42425'
num = 512341234
str(num)[-2::-2]
'3131'

But you'll have to pick -1 or -2 based on which one of those characters is in an even position (ie based on the length of the string) to do this.但是您必须根据这些字符中的哪个字符处于偶数位置(即根据字符串的长度)来选择-1-2才能执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM