使用“学习python的难题。”字符串格式化问题

问题描述 投票:-5回答:3

是他希望我输入的代码失败

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)

是看到错误并且知道他使用python 2后我修改的代码,我刚刚在网上找到它们时对代码进行了修改。

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

没有成功

python
3个回答
0
投票

你应该尝试使用string.format()

例如:

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

有关更具体的文档,请查看Format Specification Mini-Language

没关系,你的第二个例子中的问题是:

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

0
投票

正如蒂姆所说,我们可以使用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)

0
投票

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

来自sys import argv

script,user_name = argv

prompt ='>'

print(“Hi%s,Im the%s”%(user_name,script))

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

print(“你喜欢我%s”%(user_name))

likes =输入(提示)

© www.soinside.com 2019 - 2024. All rights reserved.