使用;艰苦地学习python。”;字符串格式问题

使用;艰苦地学习python。”;字符串格式问题,python,Python,他要我输入的密码失败了吗 from sys import argv script, user_name = argv prompt = '> ' print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name likes = raw_input(prompt) 是我在看到

他要我输入的密码失败了吗

from sys import argv

script, user_name = argv
prompt = '> '

print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
是我在看到错误并知道他使用Python2后修改的代码,我刚刚在网上找到他的代码时对其进行了更正

from sys import argv

script, user_name = argv
prompt = '> '

print ("Hi" user_name: %s, "I/'m the", %s: script.)
print ("I;d like tok ask you a few questions")
print ("Do you like me %s") % (user_name)
likes = input(prompt)

我的所有
%s
%d
%r
都失败了。这是python 2的约定吗?我应该用别的东西吗

比如说

foo = bar 
print ("the variable foo %s is a fundamental programming issue.)
我试过使用元组吗?例如:

print ("the variable foo", %s: foo, "is a fundamental programming issue.")
如果没有成功

您应该尝试使用

例如:

some_string = 'My name is {name} and i live in {location}'
some_params = {
    'name': 'Tim',
    'location': 'Germany'
}

print(some_string.format(**some_params))
这将导致

My name is Tim and i live in Germany
有关更具体的文档,请参阅

不过,第二个示例中的问题是:

  • 消除
    打印
    和起始支架之间的间隙
  • 在print语句之前构建字符串。有时,它看起来好像缺少
    &
    *
    %S

    • 正如蒂姆所说,我们可以使用string.format()

      对于格式化字符串,您也可以使用索引。也就是说,您的代码将如下所示

      from sys import argv
      
      script = argv[0]
      user_name = argv[1]
      
      
      print "Hi {0} I am the Script {1}".format(user_name,script)
      print ("I;d like tok ask you a few questions")
      print "Do you like me {0}".format(user_name)
      

      这将解决您的问题,因为在使用带打印的方括号时,所有格式都应在方括号内:

      从系统导入argv

      脚本,用户名=argv

      prompt='>'

      打印(“Hi%s,Im%s”%(用户名,脚本))

      打印(“我想问你几个问题”)

      打印(“您喜欢我%s%”(用户名))


      likes=input(prompt)

      请注意,在将字符串传递给
      print
      函数之前,您需要格式化字符串:
      print(“您喜欢我吗%s”%user\u name)
      。否则您将尝试
      None%user\u name
      …在
      print
      的返回值上使用
      %
      运算符。它应该是这样的:
      print(“您喜欢我%s”%user\u name)吗
      .replicate of例如,、等…谷歌搜索您的错误消息。可能的重复老实说,应该有一个标签,用于艰苦地学习Python。这是Python程序员最讨厌的五个词。虽然这肯定是一个更好的方法,但实际上并不能解释OP当前的问题。感谢您的帮助。谢谢。大家我帮了大忙。