【问题标题】:How to do string formatting with placeholders in Java (like in Python)?如何在 Java 中使用占位符进行字符串格式化(如在 Python 中)?
【发布时间】:2013-07-06 09:50:09
【问题描述】:

我是 Java 新手,来自 Python。在 Python 中,我们像这样进行字符串格式化:

>>> x = 4
>>> y = 5
>>> print("{0} + {1} = {2}".format(x, y, x + y))
4 + 5 = 9
>>> print("{} {}".format(x,y))
4 5

如何在 Java 中复制相同的东西?

【问题讨论】:

    标签: java python string format placeholder


    【解决方案1】:

    Java 有一个与此类似的String.format 方法。 Here's an example of how to use it. 这是 documentation reference,它解释了所有这些 % 选项可以是什么。

    这是一个内联示例:

    package com.sandbox;
    
    public class Sandbox {
    
        public static void main(String[] args) {
            System.out.println(String.format("It is %d oclock", 5));
        }        
    }
    

    这会打印“现在是 5 点”。

    【讨论】:

    • 这种基于%的字符串格式类似于python中使用的old-style formatting,OP使用的是new-style string formatting
    • 啊,从这个问题我不知道他如此强调使用大括号。我以为他只是想要一种在不将字符串和变量连接在一起的情况下格式化字符串的方法。
    • 感谢您的评论。否则我不会明白为什么@rgettman 会获得如此多的支持。
    【解决方案2】:

    你可以这样做(使用String.format):

    int x = 4;
    int y = 5;
    
    String res = String.format("%d + %d = %d", x, y, x+y);
    System.out.println(res); // prints "4 + 5 = 9"
    
    res = String.format("%d %d", x, y);
    System.out.println(res); // prints "4 5"
    

    【讨论】:

      【解决方案3】:

      MessageFormat 类看起来像您所追求的。

      System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
      

      【讨论】:

      • 需要注意的是MessageFormat.format 不处理空占位符{}
      • ... 并且需要注意的是,如果您使用 '{,它将无法识别括号
      【解决方案4】:

      Slf4j 有 MessageFormatter.format() 接受 {} 没有参数号,就像 Python 一样。 Slf4j 是一个流行的日志框架,但您不必使用它来进行日志记录以使用 MessageFormatter。

      【讨论】:

        【解决方案5】:

        如果你想使用空占位符(没有位置),你可以在Message.format()周围写一个小工具,像这样

            void print(String s, Object... var2) {
                int i = 0;
                while(s.contains("{}")) {
                    s = s.replaceFirst(Pattern.quote("{}"), "{"+ i++ +"}");
                }
                System.out.println(MessageFormat.format(s, var2));
            }
        

        然后,可以像这样使用它,

        print("{} + {} = {}", 4, 5, 4 + 5);
        

        【讨论】:

          【解决方案6】:

          如果您使用 Log4j 2 (log4j-api),那么您可以使用 ParameterizedMessage

          ParameterizedMessage.format("{} {}", new Object[] {x, y});
          

          new ParameterizedMessage("{} {}", x, y).getFormattedMessage(); // there is trimming
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-06-23
            • 2011-10-26
            • 2012-02-25
            • 1970-01-01
            • 1970-01-01
            • 2011-09-19
            • 2023-03-23
            相关资源
            最近更新 更多