Java 等价于 Python 的 format()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5324007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:39:21  来源:igfitidea点击:

Java equivalent of Python's format()

javastring

提问by tshepang

Here's two ways of doing string substitution:

这是进行字符串替换的两种方法:

name = "Tshepang"
"my name is {}".format(name)
"my name is " + name

How do I do something similar to the first method, using Java?

如何使用 Java 执行类似于第一种方法的操作?

回答by Pa?lo Ebermann

name = "Pa?lo";
MessageFormat f = new MessageFormat("my name is {0}");
f.format(new Object[]{name});

Or shorter:

或更短:

MessageFormat.format("my name is {0}", name);

回答by Srinivas Reddy Thatiparthy

String s = String.format("something %s","name");

回答by Valentyn Kolesnikov

Underscore-javahas a format()static method. I am the maintainer of the project. Live example

Underscore-java有一个format()静态方法。我是项目的维护者。活生生的例子

import com.github.underscore.U;

public class Main {
    public static void main(String[] args) {
        String name = "Tshepang";
        String formatted = U.format("my name is {}", name);
        // my name is Tshepang
    }
}