根据另一个字符串排序字符串

时间:2015-09-27 06:02:31

标签: python

我在我的代码中的一个地方,我需要使一个字符串中的内容顺序与另一个字符串的顺序相等。所以说你把字符串'this place'放到我的函数中你会得到TIPAEhslc返回,我想改变它的内容的顺序以匹配没有空格的原始输入字符串,所以:{{1 }}。所以,在我的代码中,使用'ThIsPlAcE'命令no_space我知道我之前已经弄明白这一点,但我不记得我是如何坚持这一点的!到目前为止,这是我的代码:

s_combine

1 个答案:

答案 0 :(得分:2)

试试这个:

def r_string(s):
    n = list()
    for i, a in enumerate(s.replace(' ', '')):
        if i%2==0:
            n.append(a.upper())
        else:
            n.append(a)

    return ''.join(n)

 print(r_string('this place'))      

输出:

#ThIsPlAcE

编辑:

我想你在寻找这个....

def r_string(s1, s2):
    #s1 is string to order
    #s2 string map to follow
    map_ = {s.lower():s.istitle() for s in s2}
    new_string = ''.join([s.upper() if map_[s] else s for s in s1.replace(' ', '')])

    return new_string

print(r_string('string me', 'TrinGsMe'))

输出:

#sTrinGMe