当前位置: 首页 > 工具软件 > PyFormat > 使用案例 >

python: PyFormat %s %d 在python string中的用法

仲孙向明
2023-12-01

%s 是从 C语言借来的 string formatting syntax;

#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)

#Python3+
name = input("who are you? ")
print("hello %s" % (name,))

The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.

其他例子:

"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".

如果包含int类型:

"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12

包含float则用 %f

 类似资料: