使用变量动态切片字符串 [英] Dynamically slice a string using a variable

查看:55
本文介绍了使用变量动态切片字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于使用变量动态切片字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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