在不省略开始和结束切片的情况下反转 Python 字符串 [英] Reverse a Python string without omitting start and end slice

查看:57
本文介绍了在不省略开始和结束切片的情况下反转 Python 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不省略开始和结束切片参数的情况下反转 Python 字符串?

word = "你好"reversed_word = word[::-1]

我知道这是可行的,但是如何通过指定开始和结束索引来获得结果?

word = "你好"reversed_word = word[?:?:-1]

很难向学生解释为什么 word[::-1] 反转字符串.如果我能给他们逻辑推理而不是这是pythonic方式"会更好.

我解释word[::1]的方式如下:你没有指定开始,所以它只是从头开始.你没有指定结束,所以它一直持续到结束.现在步长是 1,所以它只是从开始到结束 1 个字符一个 1."现在,当我的学生看到 word[::-1] 时,他们会想我们还没有指定开始或结束,所以它会一次通过字符串 -1 个字符?"

解决方案

来自 Python 2 源代码,这是用三元表达式定义的:

<块引用>

defstart = *step 0 ?长度-1:0;defstop = *step <0 ?-1:长度;

所以,当没有给出 start 和 stop 时,

如果 step 为负:

  • 开始是长度 - 1
  • stop 是 -1,(这是 C 索引,在 Python 中很难实现,必须是 -length-1)

如果步长为正:

  • 开始是 0
  • 停止是长度

所以回答这个问题:

<块引用>

如何通过指定开始和结束索引来获得结果?

要自己指定,请使用例如以下(为了可重用而放入函数中)

def my_slice(word, step):''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''s'''start = len(word)-1 如果 step <0 其他 0stop = -len(word)-1 如果 step <0 其他 len(字)返回词[开始:停止:步骤]word = "你好"步 = -1my_slice(字,步骤)

返回

'olleh'

How do you reverse a Python string without omitting the start and end slice arguments?

word = "hello"
reversed_word = word[::-1]

I understand that this works, but how would I get the result by specifying the start and end indexes?

word = "hello"
reversed_word = word[?:?:-1]

It's hard to explain to students why word[::-1] reverses a string. It's better if I can give them logical reasoning rather than "it's the pythonic way".

The way I explain word[::1] is as follows: "You have not specified the start so it just starts from the start. You have not specified the end so it just goes until the end. Now the step is 1 so it just goes from the start to the end 1 character by 1." Now when my students see word[::-1] they are going to think "We have not specified the start or the end so it will go through the string -1 characters at a time?"

解决方案

From the Python 2 source, this is defined with ternary expressions:

defstart = *step < 0 ? length-1 : 0;
defstop = *step < 0 ? -1 : length;

So, when start and stop are not given,

If step is negative:

  • start is length - 1
  • stop is -1, (this is the C index, tricky to implement in Python, must be -length-1)

If step is positive:

  • start is 0
  • stop is length

So to answer this question:

How would I get the result by specifying the start and end indexes?

To specify this yourself, use e.g. the following (put into a function for reusability)

def my_slice(word, step):
    '''slice word with only step'''
    start = len(word)-1 if step < 0 else 0
    stop = -len(word)-1 if step < 0 else len(word)
    return word[start:stop:step]


word = "hello"
step = -1
my_slice(word, step)

returns

'olleh'

这篇关于在不省略开始和结束切片的情况下反转 Python 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆