使用Python函数来改变字符串" oalalaeah"到"你好"

时间:2018-02-22 16:25:47

标签: python-3.x

您好我正在学习python我只是想解决上面的例子。这是一个函数来改变字符串" oalalaeah"到"你好"。请注意'你好'是从后面开始的备用信件。我可以单独做两件事。重要提示:我想只使用python函数()

`def rev_str(str1):
    new_str = ''
    index = len(str1)
    while index > 0:
        new_str += str1[index-1]
        index = index - 1
    return new_str`
print(rev_str('oalalaeah'))

将字符串反转为" haealalao"

以后使用:

def rev_alt(str2):
    fin_str = ''
    index = -2
    while index < len(str2)-1:
        fin_str += str2[index+2]
        index = index + 2
    return fin_str

print(rev_alt('haealalao'))

这给了我&#34;你好&#34;但这些是两个独立的操作。我希望有一个功能可以转向&#34; oalalaeah&#34;到&#34;你好&#34;。如果这太简单,我很抱歉。它让我疯狂

1 个答案:

答案 0 :(得分:2)

def rev_str(str1):
    new_str = ''
    index = len(str1)
    while index > 0:
        new_str += str1[index-1]
        index = index - 1
    return new_str

这是通过在每次迭代时将索引减1来从结尾到字符串中的每个字母。从字面上看,每个第二个字母所需的唯一更改是在每次迭代时将索引减少 2

def rev_str(str1):
    new_str = ''
    index = len(str1)
    while index > 0:
        new_str += str1[index-1]
        index = index - 2  #  here
    return new_str

print(rev_str('oalalaeah'))  # hello

这是pythonic版本的built-in slice syntax

print('oalalaeah'[::-2])  # hello