Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Python's format()

Tags:

java

string

Here's two ways of doing string substitution:

name = "Tshepang" "my name is {}".format(name) "my name is " + name 

How do I do something similar to the first method, using Java?

like image 691
tshepang Avatar asked Mar 16 '11 10:03

tshepang


People also ask

What is format in Java?

The java string format() method returns the formatted string by given locale, format and arguments. If you don't specify the locale in String. format() method, it uses default locale by calling Locale.

What is format () in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What is the alternative of format in Python?

. format() is OK, even with one variable. In python 3.6 you can also use: print(f"I am at {location} right now.")

What is the %D in Java?

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character.


2 Answers

name = "Paŭlo"; MessageFormat f = new MessageFormat("my name is {0}"); f.format(new Object[]{name}); 

Or shorter:

MessageFormat.format("my name is {0}", name); 
like image 142
Paŭlo Ebermann Avatar answered Sep 19 '22 20:09

Paŭlo Ebermann


String s = String.format("something %s","name"); 
like image 37
Srinivas Reddy Thatiparthy Avatar answered Sep 20 '22 20:09

Srinivas Reddy Thatiparthy