Write a function swap_halves(s) that takes a strin

2019-09-30 08:34发布

问题:

Write a function swap_halves(s) that takes a string s, and returns a new string in which the two halves of the string have been swapped. For example, swap_halves("good day sunshine") would return 'sunshine good day'. I tried something like

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):]  )

not sure how to do it without using if or other statements.

回答1:

I don't know what exactly you want but this might work

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 ")


回答2:

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


回答3:

You are going to want to .split() the text unless you don't mind some words getting cut say if your middle index falls in a word as someone pointed out, for string good day bad sunshine you wouldn't want 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

As requested :

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


标签: python swap