JAVA和python格式化输出
时间: 2023-10-30 14:01:35 浏览: 59
Java和Python都有自己的字符串格式化输出方法。
在Java中,常见的格式化输出方法是使用`String.format()`函数。这个函数接受一个格式字符串和要插入的变量,并返回一个格式化后的字符串。格式字符串中使用占位符 `%s`、`%d`、`%f` 等来表示要插入的变量的类型,并通过后面的参数列表传入具体的变量值。例如:
```java
String name = "John";
int age = 30;
String output = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(output);
```
这将输出:
```
My name is John and I am 30 years old.
```
而在Python中,常见的格式化输出方法有多种。其中一种方法是使用百分号 `%` 运算符来进行格式化输出。和Java类似,也使用占位符 `%s`、`%d`、`%f` 等来表示要插入的变量的类型,并通过后面的参数列表传入具体的变量值。例如:
```python
name = "John"
age = 30
output = "My name is %s and I am %d years old." % (name, age)
print(output)
```
这将输出:
```
My name is John and I am 30 years old.
```
另一种常见的格式化输出方法是使用Python 3.6及更高版本引入的 f-string。这种方法使用大括号 `{}` 作为占位符,并在前面加上字母 `f`。在大括号内可以直接引用变量,无需使用占位符。例如:
```python
name = "John"
age = 30
output = f"My name is {name} and I am {age} years old."
print(output)
```
这也将输出:
```
My name is John and I am 30 years old.
```
总结一下,Java使用`String.format()`函数进行格式化输出,而Python可以使用百分号 `%` 运算符或者 f-string 来进行格式化输出。