Python - multiple %s string

2020-07-10 03:13发布

how do you use multiple %s in a python output?

TEXT = 'Hi, your first name is %s' %Fname

This works fine but...

TEXT = 'Hi, your first name is %s and your last name is %s' %Fname %Lname

I get the error

TypeError: not enough arguments for format string

标签: python string
5条回答
smile是对你的礼貌
2楼-- · 2020-07-10 03:30

You need to use tuples:

TEXT = 'Hi, your first name is %s', % (Fname)
TEXT = 'Hi, your first name is %s and your last name is %s' % (Fname, Lname)

Also, consider using format().

查看更多
乱世女痞
3楼-- · 2020-07-10 03:41
TEXT = 'Hi, your first name is %s and your last name is %s' %(Fname, Lname)

or

TEXT ='Hi, your first name is {} and your last name is {}'.format(Fname, Lname)
查看更多
Lonely孤独者°
4楼-- · 2020-07-10 03:42

I like using string format instead.

So

TEXT = 'Hi, your first name is {} and your last name is {}'.format(Fname, Lname)
查看更多
家丑人穷心不美
5楼-- · 2020-07-10 03:43

Give all the variables in a tuple, like this:

TEXT = 'Hi, your first name is %s and your last name is %s.' %(Fname,Lname)
查看更多
欢心
6楼-- · 2020-07-10 03:46

Use a tuple:

TEXT = 'Hi, your first name is %s and your last name is %s' % (Fname, Lname)

Better: use str.format(*args, **kwargs).

"Hi, your first name is {0} and your last name is {1}".format("foo", "bar")
查看更多
登录 后发表回答