【问题标题】:Substituting variables in a string without the '+' operator在没有“+”运算符的情况下替换字符串中的变量
【发布时间】:2019-09-20 09:10:45
【问题描述】:

这个问题涉及处理代码。

我知道您可以通过执行以下操作替换字符串中的变量:

String words = "these words";
text("I want to substitute " + words + "!", textX, textY);

但是,我想知道是否有一种方法可以像我习惯在 Python 中那样做:

words = "these words";
print('I want to substitute %s!' % words);

我发现这更具可读性,因为字符串并没有像所有类型的运算符和变量那样分割。

【问题讨论】:

  • 是的,看看:String.format("I want to substitute %s!", words);

标签: java python python-3.x string formatting


【解决方案1】:

您可以为此使用String.format

String formattedString = String.format("I want to substitute %s!", words);

【讨论】:

    【解决方案2】:

    您可以在 Java 中使用printf。它在内部执行 String.format(),因此您可以使用与 Python(或任何具有类似 printf 功能的语言)几乎相同的方式进行编写。

    String words = "these words";
    System.out.printf("I want to substitute %s!", words);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2020-10-27
      • 2014-12-26
      • 2010-11-11
      相关资源
      最近更新 更多