在 Python 中使用多个参数进行字符串格式化(例如,'%s ... %s') [英] Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

查看:38
本文介绍了在 Python 中使用多个参数进行字符串格式化(例如,'%s ... %s')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像 '%s in %s' 的字符串,我想知道如何分离参数,使它们成为两个不同的 %s.我从 Java 中想到了这个:

I have a string that looks like '%s in %s' and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came up with this:

'%s in %s' % unicode(self.author),  unicode(self.publication)

但这行不通,那么它在 Python 中的表现如何?

But this doesn't work so how does it look in Python?

推荐答案

Mark Cidade 的答案是正确的 - 您需要提供一个元组.

Mark Cidade's answer is right - you need to supply a tuple.

但是,从 Python 2.6 开始,您可以使用 format 而不是 %:

However from Python 2.6 onwards you can use format instead of %:

'{0} in {1}'.format(unicode(self.author,'utf-8'),  unicode(self.publication,'utf-8'))

不再鼓励使用 % 格式化字符串.

Usage of % for formatting strings is no longer encouraged.

这种格式化字符串的方法是 Python 3.0 的新标准,应该优先于新代码中字符串格式化操作中描述的 % 格式化.

This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.

这篇关于在 Python 中使用多个参数进行字符串格式化(例如,'%s ... %s')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆