创建一个只包含奇数索引的新字符串

时间:2015-04-30 02:13:03

标签: python string loops iteration

我必须做以下事情“

编写一个以字符串作为输入的函数,并返回仅由字符串的奇数索引组成的字符串。注意:enumerate()不可用。

现在我能提出的代码是

def odd_string(data):
    result = ""
    for i in (data):
    return data[0],data[2],data[4]

print (odd_string("hello"))

我如何将这些值实际附加到字符串中?如何将其添加到每个奇数将被添加(无需全部写出)

4 个答案:

答案 0 :(得分:7)

Stride索引(你可能对它range()很熟悉)在这里工作得很好。

def odd_string(data):
    return data[1::2]

答案 1 :(得分:1)

这样的事可能吗?

def odd_string(data):
result = ''
for c in range(0, len(data)):
    if (c % 2 == 1):
        result += data[c] 
return result

答案 2 :(得分:0)

您还可以尝试以下方式:

newlist = list(range(10))
print newlist[1::2]

答案 3 :(得分:0)

$(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});