python常见的输出格式总结

1. 字符串插值/格式化字符串字面值 (f-string, Python 3.6及更高版本)

name = "World"
print(f"Hello, {name}!")

2. str.format() 方法

name = "World"
print("Hello, {}!".format(name))

或者,使用位置参数和关键字参数:

print("Hello, {0}! This is {name}.".format("World", name="Python"))

3. % 运算符

name = "World"
print("Hello, %s!" % name)

对于多个变量,可以使用元组:

x = 10
y = 20
print("x = %d, y = %d" % (x, y))

4. 模板字符串

from string import Template
name = "World"
t = Template('Hello, $name!')
print(t.substitute(name=name))

5. 使用 print() 函数的 sepend 参数

print("Hello", "World", sep=", ", end="!\n")

其中 sep 参数定义了不同项之间的分隔符,end 参数定义了字符串的结束字符。

6. 多行字符串

name = "World"
print(f"""
Hello,
{name}!
""")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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 来进行格式输出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值