开发者

Is there a Java equivalent of Python's printf hash replacement?

开发者 https://www.devze.com 2023-03-08 13:50 出处:网络
Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity).

Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity).

# hash of values
vals = {}
vals['a'] = 'a'
vals['b'] = 'b'
vals['1'] = 1

output = sys.stdout
file = open(filename).read()

print >>output, file % vals,

So in the file there are %(a), %(b), %(1) etc that I want substituted with the hash keys. I perused the API but couldn't find anything. Did I miss it or do开发者_如何学编程es something like this not exist in the Java API?


You can't do this directly without some additional templating library. I recommend StringTemplate. Very lightweight, easy to use, and very optimized and robust.


I doubt you'll find a pure Java solution that'll do exactly what you want out of the box.

With this in mind, the best answer depends on the complexity and variety of Python formatting strings that appear in your file:

  • If they're simple and not varied, the easiest way might be to code something up yourself.

  • If the opposite is true, one way to get the result you want with little work is by embedding Jython into your Java program. This will enable you to use Python's string formatting operator (%) directly. What's more, you'll be able to give it a Java Map as if it were a Python dictionary (vals in your code).

0

精彩评论

暂无评论...
验证码 换一张
取 消