Python:每日一题 80

2017-11-27 14:36:00
六月
来源:
http://bbs.fishc.com/thread-94652-1-1.html
转贴 617
题目:

写一个函数 reverse_string(string)

  1. def reverse_string(string):
  2.         pass
复制代码


该函数接收一个参数string
  • string 为一个标准的英文句子
  • 要求返回string 中每一个单词颠倒后的句子

    For example:

    1. >>> reverse_string(This is an example!')
    2. #'sihT si na !elpmaxe'
    复制代码





    答案:


    楼主解法:

    1. def reverse_string(string):
    2.         return '  '.join([''.join(list(reversed(i))) for i in string.split()])
    复制代码


    拆解开是酱紫的~

    1. def reverse_string(string):
    2.         words = string.split()#按空格将句子进行分割
    3.         temp = []
    4.         for i in words:
    5.                 each_word = ''.join(list(reversed(i))#将单词翻转并进行拼接
    6.                 temp.append(each_word)
    7.         return ''.join(temp)#将单词拼接并返回
    复制代码
  • 发表评论
    评论通过审核后显示。