不使用“+”运算符替换字符串中的变量

2024-06-16 17:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题与处理代码有关

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

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

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

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

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


Tags: to方法字符串代码textstringwordsprint
2条回答

您可以使用String.format进行以下操作:

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

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

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

相关问题 更多 >