使用变量动态切片字符串

编程入门 行业动态 更新时间:2024-10-19 16:21:56
本文介绍了使用变量动态切片字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试对字符串进行切片并将组件插入列表(或索引,集合或任何东西)中,然后进行比较,这样

I am trying to slice a string and insert the components into a list (or index, or set, or anything), then compare them, such that

输入:

abba

输出:

['ab', 'ba']

给出可变的输入长度.

所以如果我切字符串

word = raw_input("Input word" slicelength = len(word)/2 longword[:slicelength]

如此

list = [longwordleftslice] list2 = [longwordrightslice] list2 = list2[::-1 ] ## reverse slice listoverall = list + list2

但是,内置切片命令 [:i] 指定 i 是整数.

However, the built-in slice command [:i] specifies that i be an integer.

我该怎么办?

推荐答案

您始终可以做到这一点.

You can always do that..

word = "spamspamspam" first_half = word[:len(word)//2] second_half = word[len(word)//2:]

对于任何字符串 s 和任何整数 i , s == s [:i] + [:i] 是不变的.请注意,如果 len(word)是奇数,则在第二个一半"中您将获得比第一个更多的字符.

For any string s and any integer i, s == s[:i] + [:i] is invariant. Note that if len(word) is odd, you will get one more character in the second "half" than the first.

如果您使用的是python 3,请使用 input 而不是 raw_input .

If you are using python 3, use input as opposed to raw_input.

更多推荐

使用变量动态切片字符串

本文发布于:2023-11-22 06:23:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616308.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:切片   字符串   变量   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!