字符串格式中%s和%d有什么区别?

问题描述 投票:0回答:13

我不明白

%s
%d
的作用以及它们如何工作。

python string-formatting
13个回答
236
投票

它们用于格式化字符串。

%s
充当字符串的占位符,而
%d
充当数字的占位符。它们的关联值使用
%
运算符通过元组传入。

name = 'marcog'
number = 42
print '%s %d' % (name, number)

将打印

marcog 42
。请注意,名称是字符串 (%s),数字是整数(%d 表示十进制)。

有关详细信息,请参阅 https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

在 Python 3 中,示例为:

print('%s %d' % (name, number))

76
投票

来自 python 3 文档

%d
表示十进制整数

%s
适用于通用字符串或对象,如果是对象,它将转换为字符串

考虑以下代码

name ='giacomo'
number = 4.3
print('%s %s %d %f %g' % (name, number, number, number, number))

输出将是

贾科莫 4.3 4 4.300000 4.3

如您所见,

%d
将截断为整数,
%s
将保持格式,
%f
将打印为浮点数,
%g
用于通用数字

显然

print('%d' % (name))

会产生异常;您无法将字符串转换为数字


40
投票

%s
用作要注入格式化字符串的字符串值的占位符。

%d
用作数字或小数值的占位符。

例如(对于Python 3)

print ('%s is %d years old' % ('Joe', 42))

会输出

Joe is 42 years old

39
投票

这些都是信息丰富的答案,但没有一个能够完全理解

%s
%d
之间区别的核心。

%s
告诉格式化程序在参数上调用
str()
函数,并且由于我们根据定义强制转换为字符串,因此
%s
本质上只是执行
str(arg)

另一方面,

%d
,在调用
int()
之前在参数上调用
str()
,就像
str(int(arg))
一样,这将导致
int
强制转换以及
str
强制转换。

例如,我可以将十六进制值转换为十进制,

>>> '%d' % 0x15
'21'

或截断浮点数。

>>> '%d' % 34.5
'34'

但是如果参数不是数字,该操作将引发异常。

>>> '%d' % 'thirteen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

因此,如果目的只是调用

str(arg)
,那么
%s
就足够了,但是如果您需要额外的格式(例如格式化浮点小数位)或其他强制转换,则需要其他格式符号。

使用

f-string
表示法,当您省略格式化程序时,默认值为
str

>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'

string.format
也是如此;默认为
str

>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'

11
投票

这些是占位符:

例如:

'Hi %s I have %d donuts' %('Alice', 42)

这行代码将用 Alice (str) 替换 %s,用 42 替换 %d。

输出:

'Hi Alice I have 42 donuts'

大多数时候这可以通过“+”来实现。为了更深入地了解您的问题,您可能还需要检查 {} / .format()。下面是一个示例:Python 字符串格式:% 与 .format

另请参阅此处 google python 教程视频@ 40',它有一些解释 https://www.youtube.com/watch?v=tKTZoB2Vjuk


10
投票

%d
%s
字符串格式化“命令”用于格式化字符串。
%d
用于数字,
%s
用于字符串。

举个例子:

print("%s" % "hi")

print("%d" % 34.6)

传递多个参数:

print("%s %s %s%d" % ("hi", "there", "user", 123456))
将会回归
hi there user123456


9
投票

%d
%s
是占位符,它们用作可替换变量。例如,如果您创建 2 个变量

variable_one = "Stackoverflow"
variable_two = 45

您可以使用变量元组将这些变量分配给字符串中的句子。

variable_3 = "I was searching for an answer in %s and found more than %d answers to my question"

请注意,

%s
适用于字符串,
%d
适用于数字或小数变量。

如果你打印

variable_3
它看起来像这样

print(variable_3 % (variable_one, variable_two))

我在 StackOverflow 中寻找答案,并找到了超过 45 个针对我的问题的答案。


4
投票

根据最新标准,应该这样做。

print("My name is {!s} and my number is{:d}".format("Agnel Vishal",100))

请检查python3.6文档示例程序


4
投票

这是演示 Python 字符串格式和新方法的基本示例。

my_word = 'epic'
my_number = 1

print('The %s number is %d.' % (my_word, my_number))  # traditional substitution with % operator

//史诗数字是1.

print(f'The {my_word} number is {my_number}.')  # newer format string style

//史诗数字是1.

两者打印相同。


3
投票

说到这里...
python3.6 附带了

f-strings
,这使得格式化变得更加容易!
现在,如果您的 python 版本大于 3.6,您可以使用以下可用方法格式化字符串:

name = "python"

print ("i code with %s" %name)          # with help of older method
print ("i code with {0}".format(name))  # with help of format
print (f"i code with {name}")           # with help of f-strings

3
投票

%s 用于保存字符串的空间 %d 用于保存数字的空间

name = "Moses";
age = 23
print("My name is %s am CEO at MoTech Computers " %name)
print("Current am %d years old" %age)
print("So Am %s and am %d years old" %(name,age))

Program output

此视频深入探讨了该技巧 https://www.youtube.com/watch?v=4zN5YsuiqMA


2
投票

如果您想避免 %s 或 %d 那么..

name = 'marcog'
number = 42
print ('my name is',name,'and my age is:', number)

输出:

my name is marcog and my name is 42

0
投票

姓名='阿里';年龄=25;生活='德黑兰';工资=1526.73

print('%s %d 岁。她住在 %s,每月收入 %f。' % (姓名、年龄、生活、工资))

© www.soinside.com 2019 - 2024. All rights reserved.