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

问题:Python字符串格式中的%s和%d有什么区别?

我不知道该做什么%s%d做什么以及它们如何工作。

I don’t understand what %s and %d do and how they work.


回答 0

它们用于格式化字符串。%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))

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

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

will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).

See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting for details.

In Python 3 the example would be:

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

回答 1

python 3 doc

%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将打印为float并%g用于通用编号

明显

print('%d' % (name))

会产生异常;您不能将字符串转换为数字

from python 3 doc

%d is for decimal integer

%s is for generic string or object and in case of object, it will be converted to string

Consider the following code

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

the out put will be

giacomo 4.3 4 4.300000 4.3

as you can see %d will truncate to integer, %s will maintain formatting, %f will print as float and %g is used for generic number

obviously

print('%d' % (name))

will generate an exception; you cannot convert string to number


回答 2

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

%d 用作数字或十进制值的占位符。

例如(对于python 3)

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

将输出

Joe is 42 years old

%s is used as a placeholder for string values you want to inject into a formatted string.

%d is used as a placeholder for numeric or decimal values.

For example (for python 3)

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

Would output

Joe is 42 years old

回答 3

这些是占位符:

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

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

输出: 'Hi Alice I have 42 donuts'

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

在这里也可以看到@ 40’的Google python教程视频,其中有一些说明 https://www.youtube.com/watch?v=tKTZoB2Vjuk

These are placeholders:

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

This line of code will substitute %s with Alice (str) and %d with 42.

Output: 'Hi Alice I have 42 donuts'

This could be achieved with a “+” most of the time. To gain a deeper understanding to your question, you may want to check {} / .format() as well. Here is one example: Python string formatting: % vs. .format

also see here a google python tutorial video @ 40′, it has some explanations https://www.youtube.com/watch?v=tKTZoB2Vjuk


回答 4

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

例如:

print("%s" % "hi")

print("%d" % 34.6)

传递多个参数:

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

The %d and %s string formatting “commands” are used to format strings. The %d is for numbers, and %s is for strings.

For an example:

print("%s" % "hi")

and

print("%d" % 34.6)

To pass multiple arguments:

print("%s %s %s%d" % ("hi", "there", "user", 123456)) will return hi there user123456


回答 5

这些都是有根据的答案,但没有一个完全可以理解%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'

These are all informative answers, but none are quite getting at the core of what the difference is between %s and %d.

%s tells the formatter to call the str() function on the argument and since we are coercing to a string by definition, %s is essentially just performing str(arg).

%d on the other hand, is calling int() on the argument before calling str(), like str(int(arg)), This will cause int coercion as well as str coercion.

For example, I can convert a hex value to decimal,

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

or truncate a float.

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

But the operation will raise an exception if the argument isn’t a number.

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

So if the intent is just to call str(arg), then %s is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.

With the f-string notation, when you leave the formatter out, the default is 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'

The same is true with string.format; the default is str.

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

回答 6

%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个答案。

%d and %s are placeholders, they work as a replaceable variable. For example, if you create 2 variables

variable_one = "Stackoverflow"
variable_two = 45

you can assign those variables to a sentence in a string using a tuple of the variables.

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

Note that %s works for String and %d work for numerical or decimal variables.

if you print variable_3 it would look like this

print(variable_3 % (variable_one, variable_two))

I was searching for an answer in StackOverflow and found more than 45 answers to my question.


回答 7

它们是格式说明符。当您想要将Python表达式的值包含在字符串中且采用特定格式时,可以使用它们。

请参阅“ 深入Python ”以获取相对详细的介绍。

They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.

See Dive into Python for a relatively detailed introduction.


回答 8

根据最新标准,这是应该执行的操作。

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

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

As per latest standards, this is how it should be done.

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

Do check python3.6 docs and sample program


回答 9

如果您想避免使用%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

In case you would like to avoid %s or %d then..

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

Output:

my name is marcog and my name is 42

回答 10

%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))

程序输出

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

%s is used to hold space for string %d is used to hold space for number

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

this video goes deep about that tip https://www.youtube.com/watch?v=4zN5YsuiqMA


回答 11

说到哪个…
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

speaking of which …
python3.6 comes with f-strings which makes things much easier in formatting!
now if your python version is greater than 3.6 you can format your strings with these available methods:

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