Python如何将每个字母组合成一个单词?

2024-10-03 02:41:12 发布

您现在位置:Python中文网/ 问答频道 /正文

当给定名称时,例如Aberdeen Scotland

我需要得到Adbnearldteoecns的结果

把第一个字放在原处,把最后一个字倒过来,放在第一个字中间

到目前为止,我已经做了:

coordinatesf = "Aberdeen Scotland"

for line in coordinatesf:
    separate =  line.split()
    for i in separate [0:-1]:
        lastw = separate[1][::-1]
        print(i)

Tags: in名称forlinesplitprintseparateaberdeen
3条回答

这将拆分输入,将第一个单词与反向的第二个单词分开,连接成对的单词,然后连接成对的单词列表

coordinatesf = "Aberdeen Scotland"  
a,b = coordinatesf.split()
print(''.join(map(''.join, zip(a,b[::-1]))))

有点脏,但很管用:

coordinatesf = "Aberdeen Scotland"
new_word=[]
#split the two words

words = coordinatesf.split(" ")

#reverse the second and put to lowercase

words[1]=words[1][::-1].lower()

#populate the new string

for index in range(0,len(words[0])):
    new_word.insert(2*index,words[0][index])
for index in range(0,len(words[1])):
    new_word.insert(2*index+1,words[1][index])
outstring = ''.join(new_word)
print outstring

请注意,只有当输入字符串由两个长度相同的单词组成时,才需要定义好。 我用断言来确保这是真的,但你可以不说

def scramble(s):
    words = s.split(" ")
    assert len(words) == 2
    assert len(words[0]) == len(words[1])
    scrambledLetters = zip(words[0], reversed(words[1]))
    return "".join(x[0] + x[1] for x in scrambledLetters)

>>> print(scramble("Aberdeen Scotland"))
>>> AdbnearldteoecnS

可以用sum()替换x[0]+x[1]部分,但我认为这会降低可读性

相关问题 更多 >