java - Java字符串中是否有像Python中的 '%r'这样的格式说明符?

标签 java python string format

在 python 中,%r 返回 String(使用 repr() 转换任何 Python 对象)。

Java 中是否有类似的等效格式说明符?

我想要得到的是……。喜欢

String s = "String s = \"%s\";String.format(s, s)";
return String.Format(s, s);

这样,输出和输入是不同的,因为它包含转义字符\。如果我们有 %r,我们可以省略 \" 部分。

最佳答案

与 Python 的 %r 最接近的 Java 等效项是 %s%s 转换将根据参数的类型调用 formatTo()toString()

请注意,Python 的 repr() 或 Java 的 formatTo()toString() 都不对生成的内容提供任何一般保证。例如,Python 的 repr() 文档说:

"For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object."

它接着说,一个类可以覆盖默认的 repr() 行为。

在 Java 案例中,通用的 toString() javadoc 的规定性甚至更少。

"Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read."

由于 Java 中没有与 Python 的 eval() 等效的函数,因此没有通用的 Java SE 机制来提供可嵌入到生成的 Java 源代码中的转义表示。

所以简短的回答是:不。没有什么足够接近您所需要的。

关于java - Java字符串中是否有像Python中的 '%r'这样的格式说明符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59853243/

相关文章:

python - 用于非凸目标函数的 LBFGS

python - 按单词长度过滤列表

java - 为什么我的 java 应用程序模糊?

java - Android/java - 更改 Runnable 类中的按钮可见性

python - 访问动态添加的小部件(pyqt)

c - 如何只读取最后 3 位数字?

java - 如何检查字符串中的所有字符是否都是字母?

javascript - 连接附加的字符串并删除最后一个字符

java - 如何使用PDFBox获取pdf中的字符是否为粗体

java - Maven如何设置java中可见的属性