字符串函数问题

时间:2014-09-18 18:22:34

标签: python string function

尝试创建参考书目格式功能

def bibformat_mla(author,title,city,publisher,year):

    return "author. title. city: publisher, year"
    author = ('Perry')
    title = ('Personal Identity')
    city = ('London')
    publisher = ('University of California Press')
    year = (2008)
    print (author + title + city + publisher + year)

我的代码似乎无法运作。帮助

2 个答案:

答案 0 :(得分:4)

希望这会让你朝着正确的方向前进:

#! /usr/bin/env python


def bibformat_mla(author, title, city, publisher, year):
    return '%s. %s. %s: %s, %s' % (author, title, city, publisher, year)


def main():
    author = 'Perry'
    title = 'Personal Identity'
    city = 'London'
    publisher = 'University of California Press'
    year = 2008

    s = bibformat_mla(author, title, city, publisher, year)
    print s


if __name__ == '__main__':
    main()

答案 1 :(得分:3)

这里有一个重大问题。您的return位于您的函数的开头。由于return语句突破了该函数,因此您的代码永远不会超过return

您有两种可能的解决方案。

  1. return更改为print? 而不是return你可能意味着print出来:

  2. def bibformat_mla(author,title,city,publisher,year):
    
        print "author. title. city: publisher, year"
        author = ('Perry')
        title = ('Personal Identity')
        city = ('London')
        publisher = ('University of California Press')
        year = (2008)
        print (author + title + city + publisher + year)
    

    1. 移动return? 您可以将其移到底部,而不是将return保留在函数的顶部:

    2. def bibformat_mla(author,title,city,publisher,year):
      
          author = ('Perry')
          title = ('Personal Identity')
          city = ('London')
          publisher = ('University of California Press')
          year = (2008)
          print (author + title + city + publisher + year)
          return "author. title. city: publisher, year"