编写一个带有字符串s的函数swap_halves,并返回一个新的字符串,其中字符串的两半已被交换

问题描述 投票:-4回答:3

写一个函数swap_halves(s),它接受一个字符串s,并返回一个新的字符串,其中字符串的两半已被交换。例如,swap_halves("good day sunshine")将返回'sunshine good day'。我试过类似的东西

def swap_halves (s):
    '''Returns a new string in which the two halves of the spring have swapped'''

    return (s[0:len(s)] + s[len(s):]  )

不知道怎么做而不使用if或其他声明。

python swap
3个回答
1
投票

我不知道你到底想要什么,但这可能有用

def swap_halves (s):
  '''Returns a new string in which the two halves of the spring have swapped'''
  i = int(len(s)/2)
  print(s[i:] + s[:i]  )
swap_halves("good day sunshine ")

1
投票
def func(s):
    return(s[0:1]*3+s[1:]+s[-1:]*3)

0
投票

你会想要.split()文本,除非你不介意一些词得到削减说如果你的中间索引落在一个单词指出,一个字符串good day bad sunshine你不会想要ad sunshinegood day b

def swapper(some_string):
    words = some_string.split()
    mid = int(len(words)/2)
    new = words[mid:] + words[:mid]
    return ' '.join(new)

print(swapper('good day bad sunshine'))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 images.py
bad sunshine good day

按照要求 :

def tripler(text):
    new = text[:1] * 3 + text[1:-1] + text[-1:] * 3
    return new

print(tripler('cayenne'))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 images.py
cccayenneee
© www.soinside.com 2019 - 2024. All rights reserved.