.format代码仅显示首字母

时间:2018-11-08 01:49:45

标签: python python-3.x

由于某种原因,控制台仅显示阅读器输入内容的首字母。为什么会这样?

代码如下:

PRIVATE and PUBLIC

2 个答案:

答案 0 :(得分:0)

在格式调用的开头,您需要删除一个星号(*):

print(string.format(string1,string2,string3,string4,string5,string6))

星号是您如何解包函数的参数,在这种情况下,您不需要这样做。您的字符串中还有7个占位符,但仅将6个变量传递给format调用。如果您使用的是Python 3.6及更高版本,则应改用f-strings(它们确实很棒):

print(f"Be kind to your {string1}-footed {string2} For a duck "
      f"may be somebody's {string3}, Be kind to your {string4} "
      f"in {string5} Where the weather is always {string6}. "
      f"You may think that this is the {string7}, Well it is.")

F字符串使这种错误很难引入。

答案 1 :(得分:0)

*之前的string1将该字符串的元素扩展为单独的参数。所以等于:

print(string.format(string1[0], string1[1], string1[2], ...,string2,string3,string4,string5,string6))

有关函数定义和参数列表中*的含义,请参见What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

摆脱它。

print(string.format(string1,string2,string3,string4,string5,string6))

但是现在您没有足够的字符串来容纳格式字符串中的所有占位符。您缺少Be kind to your {} in的名词。所以应该是:

print ('Welcome to MadLibs')
string1 = input('Noun')
string2 = input('Plural Noun')
string3 = input('Noun')
string4 = input('Noun')
string5 = input('Place')
string6 = input('Adjective')
string7 = input('Noun')
string='Be kind to your {}-footed {} For a duck may be somebody\'s {}, Be kind to your {} in {} Where the weather is always {}. You may think that this is the {}, Well it is.'
print(string.format(string1,string2,string3,string4,string5,string6,string7))