在Python中返回格式化的字符串 [英] Return formatted string in Python

查看:77
本文介绍了在Python中返回格式化的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

testString = """ My name is %s
and I am %s years old
and I live in %s"""

我有找到可以输入到testString的这三个字符串的代码.我怎么做?在Java中,我会这样做:

I have code that finds these three strings that I want to input into testString. How do I do that? In Java I would've done:

return String.format(testString, string1, string2, string3)

Python是否有等效功能?

Is there an equivalent in Python?

推荐答案

这是使用的版本:

print """ My name is %s
and I am %s years old
and I live in %s""" % ('tim', 6, 'new york')

这是我的首选版本:

testString = """ My name is {}
and I am {} years old
and I live in {}""".format(string1, string2, string3)

您可能想阅读 https://docs.python.org/3.4/library/string.html#string-formatting .

这篇关于在Python中返回格式化的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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