标签归档:integer

如何在Python中将字符转换为整数,反之亦然?

问题:如何在Python中将字符转换为整数,反之亦然?

我想要获得一个角色的ASCII价值。

例如,对于角色a,我要获取97,反之亦然。

I want to get, given a character, its ASCII value.

For example, for the character a, I want to get 97, and vice versa.


回答 0

使用chr()ord()

>>> chr(97)
'a'
>>> ord('a')
97

Use chr() and ord():

>>> chr(97)
'a'
>>> ord('a')
97

回答 1

>>> ord('a')
97
>>> chr(97)
'a'
>>> ord('a')
97
>>> chr(97)
'a'

回答 2

ord和chr


您如何用Python表达二进制文字?

问题:您如何用Python表达二进制文字?

如何使用Python文字将整数表示为二进制数?

我很容易找到十六进制的答案:

>>> 0x12AF
4783
>>> 0x100
256

和八进制:

>>> 01267
695
>>> 0100
64

您如何使用文字在Python中表示二进制?


答案摘要

  • Python 2.5及更早版本:可以使用,int('01010101111',2)但不能使用文字来表示二进制。
  • Python 2.5和更早版本:无法表达二进制文字。
  • Python 2.6 beta:您可以这样做:0b11001110B1100111
  • Python 2.6 beta:还将允许0o270O27(第二个字符是字母O)表示一个八进制。
  • Python 3.0 beta:与2.6相同,但将不再允许使用较旧027的八进制语法。

How do you express an integer as a binary number with Python literals?

I was easily able to find the answer for hex:

>>> 0x12AF
4783
>>> 0x100
256

and octal:

>>> 01267
695
>>> 0100
64

How do you use literals to express binary in Python?


Summary of Answers

  • Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal.
  • Python 2.5 and earlier: there is no way to express binary literals.
  • Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111.
  • Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal.
  • Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals.

回答 0

供参考- 未来的 Python可能性:
从Python 2.6开始,您可以使用前缀0b0B表示二进制文字:

>>> 0b101111
47

您还可以使用新的bin函数来获取数字的二进制表示形式:

>>> bin(173)
'0b10101101'

文档的开发版本:Python 2.6的新增功能

For reference—future Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B:

>>> 0b101111
47

You can also use the new bin function to get the binary representation of a number:

>>> bin(173)
'0b10101101'

Development version of the documentation: What’s New in Python 2.6


回答 1

>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255

另一种方式。

>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255

Another way.


回答 2

您如何用Python表达二进制文字?

它们不是“二进制”文字,而是“整数文字”。您可以用二进制格式表示整数文字,0后跟a Bb后跟一系列零和一,例如:

>>> 0b0010101010
170
>>> 0B010101
21

从Python 3 文档开始,以下是在Python中提供整数文字的方式:

整数文字由以下词汇定义描述:

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::=  "1"..."9"
digit        ::=  "0"..."9"
bindigit     ::=  "0" | "1"
octdigit     ::=  "0"..."7"
hexdigit     ::=  digit | "a"..."f" | "A"..."F"

除了可以存储在可用内存中的整数之外,整数字面量的长度没有限制。

请注意,不允许使用非零十进制数字开头的零。这是为了消除C样式八进制文字的歧义,Python在3.0版之前使用了这些文字。

整数文字的一些示例:

7     2147483647                        0o177    0b100110111
3     79228162514264337593543950336     0o377    0xdeadbeef
      100_000_000_000                   0b_1110_0101

在版本3.6中进行了更改:现在允许在文本中使用下划线进行分组。

其他表达二进制的方式:

您可以在可操作的字符串对象中包含零和一(尽管在大多数情况下,您可能应该对整数进行按位运算)-只需将零和一的字符串以及您要从中转换的基数传递给int ):

>>> int('010101', 2)
21

您可以选择使用0b0B前缀:

>>> int('0b0010101010', 2)
170

如果将其0作为基数传递,则如果字符串未指定前缀,则它将假定基数为10:

>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21

从int转换回人类可读的二进制文件:

您可以将整数传递给bin以查看二进制文字的字符串表示形式:

>>> bin(21)
'0b10101'

你可以结合binint去来回:

>>> bin(int('010101', 2))
'0b10101'

如果希望最小宽度和前面的零,也可以使用格式规范:

>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'

How do you express binary literals in Python?

They’re not “binary” literals, but rather, “integer literals”. You can express integer literals with a binary format with a 0 followed by a B or b followed by a series of zeros and ones, for example:

>>> 0b0010101010
170
>>> 0B010101
21

From the Python 3 docs, these are the ways of providing integer literals in Python:

Integer literals are described by the following lexical definitions:

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::=  "1"..."9"
digit        ::=  "0"..."9"
bindigit     ::=  "0" | "1"
octdigit     ::=  "0"..."7"
hexdigit     ::=  digit | "a"..."f" | "A"..."F"

There is no limit for the length of integer literals apart from what can be stored in available memory.

Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

Some examples of integer literals:

7     2147483647                        0o177    0b100110111
3     79228162514264337593543950336     0o377    0xdeadbeef
      100_000_000_000                   0b_1110_0101

Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.

Other ways of expressing binary:

You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) – just pass int the string of zeros and ones and the base you are converting from (2):

>>> int('010101', 2)
21

You can optionally have the 0b or 0B prefix:

>>> int('0b0010101010', 2)
170

If you pass it 0 as the base, it will assume base 10 if the string doesn’t specify with a prefix:

>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21

Converting from int back to human readable binary:

You can pass an integer to bin to see the string representation of a binary literal:

>>> bin(21)
'0b10101'

And you can combine bin and int to go back and forth:

>>> bin(int('010101', 2))
'0b10101'

You can use a format specification as well, if you want to have minimum width with preceding zeros:

>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'

回答 3

开头的0表示底数是8(而不是10),这很容易看到:

>>> int('010101', 0)
4161

如果您不以0开头,则python假定数字以10为底。

>>> int('10101', 0)
10101

0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:

>>> int('010101', 0)
4161

If you don’t start with a 0, then python assumes the number is base 10.

>>> int('10101', 0)
10101

回答 4

据我所知,直到2.5,Python仅支持十六进制和八进制文字。我确实找到了一些有关在将来的版本中添加二进制文件的讨论,但没有明确的定义。

As far as I can tell Python, up through 2.5, only supports hexadecimal & octal literals. I did find some discussions about adding binary to future versions but nothing definite.


回答 5

我很确定这是由于Python 3.0的变化之一,也许bin()与hex()和oct()一起使用。

编辑:lbrandy的答案在所有情况下都是正确的。

I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().

EDIT: lbrandy’s answer is correct in all cases.


如何在Python中四舍五入一个数字?

问题:如何在Python中四舍五入一个数字?

这个问题使我丧命。如何在Python中向上舍入一个数字?

我尝试了舍入(数字),但它四舍五入数字。例:

round(2.3) = 2.0 and not 3, what I would like

我尝试了int(number + .5),但是它再次将数字取整!例:

int(2.3 + .5) = 2

然后我尝试了round(number + .5),但在边缘情况下不起作用。例:

WAIT! THIS WORKED!

请指教。

This problem is killing me. How does one roundup a number UP in Python?

I tried round(number) but it round the number down. Example:

round(2.3) = 2.0 and not 3, what I would like

The I tried int(number + .5) but it round the number down again! Example:

int(2.3 + .5) = 2

Then I tried round(number + .5) but it won’t work in edge cases. Example:

WAIT! THIS WORKED!

Please advise.


回答 0

小区(上限)功能:

import math
print(math.ceil(4.2))

The ceil (ceiling) function:

import math
print(math.ceil(4.2))

回答 1

我知道这个答案是一个很久以前的问题,但是如果您不想导入数学并且只想四舍五入,那么这对我有用。

>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5

如果有余数,则第一部分将变为4,第二部分将得出“ True”,另外,True = 1; False =0。因此,如果没有余数,则它将保持相同的整数,但是如果有余数,则将其加1。

I know this answer is for a question from a while back, but if you don’t want to import math and you just want to round up, this works for me.

>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5

The first part becomes 4 and the second part evaluates to “True” if there is a remainder, which in addition True = 1; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1.


回答 2

请记住有趣的Python 2.x问题:

>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0

问题是在python中将两个int相除会产生另一个int,并且在上限调用之前被截断了。您必须使一个值成为浮点数(或强制转换)才能获得正确的结果。

在javascript中,完全相同的代码会产生不同的结果:

console.log(Math.ceil(4500/1000));
5

Interesting Python 2.x issue to keep in mind:

>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0

The problem is that dividing two ints in python produces another int and that’s truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.

In javascript, the exact same code produces a different result:

console.log(Math.ceil(4500/1000));
5

回答 3

如果使用整数,则四舍五入的一种方法是利用四舍五入的事实//:只需对负数进行除法,然后取反即可。无需导入,浮点或有条件的。

rounded_up = -(-numerator // denominator)

例如:

>>> print(-(-101 // 5))
21

If working with integers, one way of rounding up is to take advantage of the fact that // rounds down: Just do the division on the negative number, then negate the answer. No import, floating point, or conditional needed.

rounded_up = -(-numerator // denominator)

For example:

>>> print(-(-101 // 5))
21

回答 4

您可能还喜欢numpy:

>>> import numpy as np
>>> np.ceil(2.3)
3.0

我并不是说它比数学更好,但是如果您已经将numpy用于其他目的,则可以使代码保持一致。

无论如何,我遇到的只是一个细节。我经常使用numpy,但感到惊讶的是它没有被提及,但是当然可以接受。

You might also like numpy:

>>> import numpy as np
>>> np.ceil(2.3)
3.0

I’m not saying it’s better than math, but if you were already using numpy for other purposes, you can keep your code consistent.

Anyway, just a detail I came across. I use numpy a lot and was surprised it didn’t get mentioned, but of course the accepted answer works perfectly fine.


回答 5

使用math.ceil围捕:

>>> import math
>>> math.ceil(5.4)
6.0

注意:输入应为浮点型。

如果需要整数,请调用int将其转换:

>>> int(math.ceil(5.4))
6

BTW,使用math.floor到轮,并round以轮最接近的整数。

>>> math.floor(4.4), math.floor(4.5), math.floor(5.4), math.floor(5.5)
(4.0, 4.0, 5.0, 5.0)
>>> round(4.4), round(4.5), round(5.4), round(5.5)
(4.0, 5.0, 5.0, 6.0)
>>> math.ceil(4.4), math.ceil(4.5), math.ceil(5.4), math.ceil(5.5)
(5.0, 5.0, 6.0, 6.0)

Use math.ceil to round up:

>>> import math
>>> math.ceil(5.4)
6.0

NOTE: The input should be float.

If you need an integer, call int to convert it:

>>> int(math.ceil(5.4))
6

BTW, use math.floor to round down and round to round to nearest integer.

>>> math.floor(4.4), math.floor(4.5), math.floor(5.4), math.floor(5.5)
(4.0, 4.0, 5.0, 5.0)
>>> round(4.4), round(4.5), round(5.4), round(5.5)
(4.0, 5.0, 5.0, 6.0)
>>> math.ceil(4.4), math.ceil(4.5), math.ceil(5.4), math.ceil(5.5)
(5.0, 5.0, 6.0, 6.0)

回答 6

语法可能不像pythonic那样,但是它是一个功能强大的库。

https://docs.python.org/2/library/decimal.html

from decimal import *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))

The syntax may not be as pythonic as one might like, but it is a powerful library.

https://docs.python.org/2/library/decimal.html

from decimal import *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))

回答 7

我很惊讶没有人建议

(numerator + denominator - 1) // denominator

用于四舍五入的整数除法。曾经是C / C ++ / CUDA的常用方法(参见divup

I am surprised nobody suggested

(numerator + denominator - 1) // denominator

for integer division with rounding up. Used to be the common way for C/C++/CUDA (cf. divup)


回答 8

请确保四舍五入的值应为浮点型

a = 8 
b = 21
print math.ceil(a / b)
>>> 0

print math.ceil(float(a) / b)
>>> 1.0

Be shure rounded value should be float

a = 8 
b = 21
print math.ceil(a / b)
>>> 0

but

print math.ceil(float(a) / b)
>>> 1.0

回答 9

尝试这个:

a = 211.0
print(int(a) + ((int(a) - a) != 0))

Try this:

a = 211.0
print(int(a) + ((int(a) - a) != 0))

回答 10

>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

此功能不需要任何模块。

>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

This function requires no modules.


回答 11

上面的答案是正确的,但是,math对于这个功能而言,导入模块通常对我来说有点过头了。幸运的是,还有另一种方法可以做到:

g = 7/5
g = int(g) + (not g.is_integer())

True并且在python中涉及数字的语句中False被解释为10g.is_interger()基本上翻译为g.has_no_decimal()g == int(g)。因此,最后的英文陈述为round g down and add one if g has decimal

The above answers are correct, however, importing the math module just for this one function usually feels like a bit of an overkill for me. Luckily, there is another way to do it:

g = 7/5
g = int(g) + (not g.is_integer())

True and False are interpreted as 1 and 0 in a statement involving numbers in python. g.is_interger() basically translates to g.has_no_decimal() or g == int(g). So the last statement in English reads round g down and add one if g has decimal.


回答 12

无需导入数学//使用基本环境:

a)方法/类方法

def ceil(fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

def ceil(self, fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

b)lambda:

ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)

Without importing math // using basic envionment:

a) method / class method

def ceil(fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

def ceil(self, fl): 
  return int(fl) + (1 if fl-int(fl) else 0)

b) lambda:

ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)

回答 13

对于那些想要四舍五入a / b并获得整数的人:

使用整数除法的另一个变体是

def int_ceil(a, b):
    return (a - 1) // b + 1

>>> int_ceil(19, 5)
4
>>> int_ceil(20, 5)
4
>>> int_ceil(21, 5)
5

For those who want to round up a / b and get integer:

Another variant using integer division is

def int_ceil(a, b):
    return (a - 1) // b + 1

>>> int_ceil(19, 5)
4
>>> int_ceil(20, 5)
4
>>> int_ceil(21, 5)
5

回答 14

如果有人希望将其舍入到小数点后一位:

import math
def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

In case anyone is looking to round up to a specific decimal place:

import math
def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

回答 15

令我惊讶的是我还没有看到这个答案round(x + 0.4999),所以我要把它放下来。请注意,这适用于任何Python版本。对Python舍入方案的更改使事情变得困难。看到这篇文章

不导入,我使用:

def roundUp(num):
    return round(num + 0.49)

testCases = list(x*0.1 for x in range(0, 50))

print(testCases)
for test in testCases:
    print("{:5.2f}  -> {:5.2f}".format(test, roundUp(test)))

为什么这样

来自文档

对于支持round()的内置类型,将值四舍五入为乘幂n的最接近10的倍数;如果两个倍数相等接近,则四舍五入取整为偶数选择

因此,将2.5舍入为2,将3.5舍入为4。如果不是这种情况,则可以通过加0.5来舍入,但是我们要避免到达中间点。因此,如果添加0.4999,您将接近,但有足够的余量可以四舍五入到通常的期望值。当然,如果x + 0.4999等于,这将失败[n].5000,但这不太可能。

I’m surprised I haven’t seen this answer yet round(x + 0.4999), so I’m going to put it down. Note that this works with any Python version. Changes made to the Python rounding scheme has made things difficult. See this post.

Without importing, I use:

def roundUp(num):
    return round(num + 0.49)

testCases = list(x*0.1 for x in range(0, 50))

print(testCases)
for test in testCases:
    print("{:5.2f}  -> {:5.2f}".format(test, roundUp(test)))

Why this works

From the docs

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done toward the even choice

Therefore 2.5 gets rounded to 2 and 3.5 gets rounded to 4. If this was not the case then rounding up could be done by adding 0.5, but we want to avoid getting to the halfway point. So, if you add 0.4999 you will get close, but with enough margin to be rounded to what you would normally expect. Of course, this will fail if the x + 0.4999 is equal to [n].5000, but that is unlikely.


回答 16

要做到这一点而无需任何导入:

>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3

To do it without any import:

>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3

回答 17

我知道这已经有一段时间了,但是我找到了一个非常有趣的答案,所以可以这样:

-round(-x-0.5)

这可以修复边缘情况,并且适用于正数和负数,并且不需要任何函数导入

干杯

I know this is from quite a while back, but I found a quite interesting answer, so here goes:

-round(-x-0.5)

This fixes the edges cases and works for both positive and negative numbers, and doesn’t require any function import

Cheers


回答 18

当您在python中操作4500/1000时,结果将为4,因为默认情况下python假定结果为整数,逻辑上:4500/1000 = 4.5-> int(4.5)= 4且ceil显然为4

使用4500 / 40.0的结果将是4.5且ceil为4.5-> 5

使用javascript,您将收到4.5的4500/1000结果,因为javascript仅将结果视为“数值类型”,并将结果直接返回为float

祝好运!!

when you operate 4500/1000 in python, result will be 4, because for default python asume as integer the result, logically: 4500/1000 = 4.5 –> int(4.5) = 4 and ceil of 4 obviouslly is 4

using 4500/1000.0 the result will be 4.5 and ceil of 4.5 –> 5

Using javascript you will recieve 4.5 as result of 4500/1000, because javascript asume only the result as “numeric type” and return a result directly as float

Good Luck!!


回答 19

如果您不想导入任何内容,则可以始终将自己的简单函数编写为:

def RoundUP(num): if num== int(num): return num return int(num + 1)

If you don’t want to import anything, you can always write your own simple function as:

def RoundUP(num): if num== int(num): return num return int(num + 1)


回答 20

您可以使用楼层划分并将其添加1。2.3 // 2 + 1

You can use floor devision and add 1 to it. 2.3 // 2 + 1


回答 21

我认为您会混淆int()和之间的工作机制round()

int()如果给出浮点数,则总是截断十进制数;相反round(),如果2.5where 23are都在等距离内2.5,则Python返回距离0点更远的那个。

round(2.5) = 3
int(2.5) = 2

I think you are confusing the working mechanisms between int() and round().

int() always truncates the decimal numbers if a floating number is given; whereas round(), in case of 2.5 where 2 and 3 are both within equal distance from 2.5, Python returns whichever that is more away from the 0 point.

round(2.5) = 3
int(2.5) = 2

回答 22

我的份额

我已经测试 print(-(-101 // 5)) = 21了上面给出的示例。

现在进行四舍五入:

101 * 19% = 19.19

我不能使用,**所以我将乘法扩展到除法:

(-(-101 //(1/0.19))) = 20

My share

I have tested print(-(-101 // 5)) = 21 given example above.

Now for rounding up:

101 * 19% = 19.19

I can not use ** so I spread the multiply to division:

(-(-101 //(1/0.19))) = 20

回答 23

我基本上是Python的初学者,但是如果您只是想舍入而不是舍弃,那为什么不做:

round(integer) + 1

I’m basically a beginner at Python, but if you’re just trying to round up instead of down why not do:

round(integer) + 1

如何在不使用try / except的情况下检查字符串是否表示int?

问题:如何在不使用try / except的情况下检查字符串是否表示int?

有没有办法在不使用try / except机制的情况下判断字符串是否表示一个整数(例如'3''-17'但不是'3.14''asfasfas')?

is_int('3.14') = False
is_int('-7')   = True

Is there any way to tell whether a string represents an integer (e.g., '3', '-17' but not '3.14' or 'asfasfas') Without using a try/except mechanism?

is_int('3.14') = False
is_int('-7')   = True

回答 0

如果您真的很讨厌在try/except各处使用s,请编写一个辅助函数:

def RepresentsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False

要完全覆盖Python认为整数的所有字符串,将需要更多的代码。我说这是pythonic。

If you’re really just annoyed at using try/excepts all over the place, please just write a helper function:

def RepresentsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False

It’s going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one.


回答 1

使用正整数可以使用.isdigit

>>> '16'.isdigit()
True

它不适用于负整数。假设您可以尝试以下操作:

>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True

它不适用于'16.0'格式,int在这种意义上类似于强制转换。

编辑

def check_int(s):
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()

with positive integers you could use .isdigit:

>>> '16'.isdigit()
True

it doesn’t work with negative integers though. suppose you could try the following:

>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True

it won’t work with '16.0' format, which is similar to int casting in this sense.

edit:

def check_int(s):
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()

回答 2

您知道,无论出于何种原因,我都发现(并且已经对此进行了反复测试)try / except的效果并不理想。我经常尝试几种做事方法,但我认为我从来没有找到一种使用try / except来最好地完成那些测试的方法,实际上,在我看来,这些方法通常已经接近于最糟糕的,即使不是最糟糕的。并非在每种情况下,但在许多情况下。我知道很多人说这是“ Pythonic”方式,但这是我与他们分开的一个领域。对我来说,它既不是很好的表现也不是非常优雅,因此,我倾向于只将其用于错误捕获和报告。

我要抱怨的是,PHP,perl,ruby,C,甚至是怪异的shell都具有简单的功能来测试整数整数字符串,但是尽力验证这些假设使我大跌眼镜!显然,这种缺乏是一种常见的疾病。

这是布鲁诺帖子的快速而肮脏的编辑:

import sys, time, re

g_intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")

testvals = [
    # integers
    0, 1, -1, 1.0, -1.0,
    '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06',
    # non-integers
    'abc 123',
    1.1, -1.1, '1.1', '-1.1', '+1.1',
    '1.1.1', '1.1.0', '1.0.1', '1.0.0',
    '1.0.', '1..0', '1..',
    '0.0.', '0..0', '0..',
    'one', object(), (1,2,3), [1,2,3], {'one':'two'},
    # with spaces
    ' 0 ', ' 0.', ' .0','.01 '
]

def isInt_try(v):
    try:     i = int(v)
    except:  return False
    return True

def isInt_str(v):
    v = str(v).strip()
    return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

def isInt_re(v):
    import re
    if not hasattr(isInt_re, 'intRegex'):
        isInt_re.intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
    return isInt_re.intRegex.match(str(v).strip()) is not None

def isInt_re2(v):
    return g_intRegex.match(str(v).strip()) is not None

def check_int(s):
    s = str(s)
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()    


def timeFunc(func, times):
    t1 = time.time()
    for n in range(times):
        for v in testvals: 
            r = func(v)
    t2 = time.time()
    return t2 - t1

def testFuncs(funcs):
    for func in funcs:
        sys.stdout.write( "\t%s\t|" % func.__name__)
    print()
    for v in testvals:
        if type(v) == type(''):
            sys.stdout.write("'%s'" % v)
        else:
            sys.stdout.write("%s" % str(v))
        for func in funcs:
            sys.stdout.write( "\t\t%s\t|" % func(v))
        sys.stdout.write("\r\n") 

if __name__ == '__main__':
    print()
    print("tests..")
    testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2, check_int))
    print()

    print("timings..")
    print("isInt_try:   %6.4f" % timeFunc(isInt_try, 10000))
    print("isInt_str:   %6.4f" % timeFunc(isInt_str, 10000)) 
    print("isInt_re:    %6.4f" % timeFunc(isInt_re, 10000))
    print("isInt_re2:   %6.4f" % timeFunc(isInt_re2, 10000))
    print("check_int:   %6.4f" % timeFunc(check_int, 10000))

性能比较结果如下:

timings..
isInt_try:   0.6426
isInt_str:   0.7382
isInt_re:    1.1156
isInt_re2:   0.5344
check_int:   0.3452

AC方法可以扫描一次并完成。我认为,一次扫描字符串的AC方法将是正确的做法。

编辑:

我已经更新了上面的代码以在Python 3.5中工作,并包括了当前投票最多的答案中的check_int函数,并使用了我可以找到的当前最流行的正则表达式来测试整数罩。此正则表达式拒绝诸如“ abc 123”之类的字符串。我添加了“ abc 123”作为测试值。

在这一点上,我非常感兴趣的是要注意,没有一个测试的函数(包括try方法,流行的check_int函数和最流行的用于测试整数罩的正则表达式)会返回所有正确的答案。测试值(嗯,取决于您认为正确答案是什么;请参阅下面的测试结果)。

内置的int()函数会默默地截断浮点数的小数部分,并返回小数点前的整数部分,除非首先将浮点数转换为字符串。

check_int()函数对于0.0和1.0(在技术上是整数)之类的值返回false,对于“ 06”之类的值返回true。

以下是当前(Python 3.5)的测试结果:

                  isInt_try |       isInt_str       |       isInt_re        |       isInt_re2       |   check_int   |
    0               True    |               True    |               True    |               True    |       True    |
    1               True    |               True    |               True    |               True    |       True    |
    -1              True    |               True    |               True    |               True    |       True    |
    1.0             True    |               True    |               False   |               False   |       False   |
    -1.0            True    |               True    |               False   |               False   |       False   |
    '0'             True    |               True    |               True    |               True    |       True    |
    '0.'            False   |               True    |               False   |               False   |       False   |
    '0.0'           False   |               True    |               False   |               False   |       False   |
    '1'             True    |               True    |               True    |               True    |       True    |
    '-1'            True    |               True    |               True    |               True    |       True    |
    '+1'            True    |               True    |               True    |               True    |       True    |
    '1.0'           False   |               True    |               False   |               False   |       False   |
    '-1.0'          False   |               True    |               False   |               False   |       False   |
    '+1.0'          False   |               True    |               False   |               False   |       False   |
    '06'            True    |               True    |               False   |               False   |       True    |
    'abc 123'       False   |               False   |               False   |               False   |       False   |
    1.1             True    |               False   |               False   |               False   |       False   |
    -1.1            True    |               False   |               False   |               False   |       False   |
    '1.1'           False   |               False   |               False   |               False   |       False   |
    '-1.1'          False   |               False   |               False   |               False   |       False   |
    '+1.1'          False   |               False   |               False   |               False   |       False   |
    '1.1.1'         False   |               False   |               False   |               False   |       False   |
    '1.1.0'         False   |               False   |               False   |               False   |       False   |
    '1.0.1'         False   |               False   |               False   |               False   |       False   |
    '1.0.0'         False   |               False   |               False   |               False   |       False   |
    '1.0.'          False   |               False   |               False   |               False   |       False   |
    '1..0'          False   |               False   |               False   |               False   |       False   |
    '1..'           False   |               False   |               False   |               False   |       False   |
    '0.0.'          False   |               False   |               False   |               False   |       False   |
    '0..0'          False   |               False   |               False   |               False   |       False   |
    '0..'           False   |               False   |               False   |               False   |       False   |
    'one'           False   |               False   |               False   |               False   |       False   |
    <obj..>         False   |               False   |               False   |               False   |       False   |
    (1, 2, 3)       False   |               False   |               False   |               False   |       False   |
    [1, 2, 3]       False   |               False   |               False   |               False   |       False   |
    {'one': 'two'}  False   |               False   |               False   |               False   |       False   |
    ' 0 '           True    |               True    |               True    |               True    |       False   |
    ' 0.'           False   |               True    |               False   |               False   |       False   |
    ' .0'           False   |               False   |               False   |               False   |       False   |
    '.01 '          False   |               False   |               False   |               False   |       False   |

刚才我尝试添加此功能:

def isInt_float(s):
    try:
        return float(str(s)).is_integer()
    except:
        return False

它的性能几乎与check_int(0.3486)一样好,并且对于1.0和0.0以及+1.0和0和.0等值返回true。但是它对于’06’也返回true,因此。我猜,选择你的毒药。

You know, I’ve found (and I’ve tested this over and over) that try/except does not perform all that well, for whatever reason. I frequently try several ways of doing things, and I don’t think I’ve ever found a method that uses try/except to perform the best of those tested, in fact it seems to me those methods have usually come out close to the worst, if not the worst. Not in every case, but in many cases. I know a lot of people say it’s the “Pythonic” way, but that’s one area where I part ways with them. To me, it’s neither very performant nor very elegant, so, I tend to only use it for error trapping and reporting.

I was going to gripe that PHP, perl, ruby, C, and even the freaking shell have simple functions for testing a string for integer-hood, but due diligence in verifying those assumptions tripped me up! Apparently this lack is a common sickness.

Here’s a quick and dirty edit of Bruno’s post:

import sys, time, re

g_intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")

testvals = [
    # integers
    0, 1, -1, 1.0, -1.0,
    '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06',
    # non-integers
    'abc 123',
    1.1, -1.1, '1.1', '-1.1', '+1.1',
    '1.1.1', '1.1.0', '1.0.1', '1.0.0',
    '1.0.', '1..0', '1..',
    '0.0.', '0..0', '0..',
    'one', object(), (1,2,3), [1,2,3], {'one':'two'},
    # with spaces
    ' 0 ', ' 0.', ' .0','.01 '
]

def isInt_try(v):
    try:     i = int(v)
    except:  return False
    return True

def isInt_str(v):
    v = str(v).strip()
    return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

def isInt_re(v):
    import re
    if not hasattr(isInt_re, 'intRegex'):
        isInt_re.intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
    return isInt_re.intRegex.match(str(v).strip()) is not None

def isInt_re2(v):
    return g_intRegex.match(str(v).strip()) is not None

def check_int(s):
    s = str(s)
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()    


def timeFunc(func, times):
    t1 = time.time()
    for n in range(times):
        for v in testvals: 
            r = func(v)
    t2 = time.time()
    return t2 - t1

def testFuncs(funcs):
    for func in funcs:
        sys.stdout.write( "\t%s\t|" % func.__name__)
    print()
    for v in testvals:
        if type(v) == type(''):
            sys.stdout.write("'%s'" % v)
        else:
            sys.stdout.write("%s" % str(v))
        for func in funcs:
            sys.stdout.write( "\t\t%s\t|" % func(v))
        sys.stdout.write("\r\n") 

if __name__ == '__main__':
    print()
    print("tests..")
    testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2, check_int))
    print()

    print("timings..")
    print("isInt_try:   %6.4f" % timeFunc(isInt_try, 10000))
    print("isInt_str:   %6.4f" % timeFunc(isInt_str, 10000)) 
    print("isInt_re:    %6.4f" % timeFunc(isInt_re, 10000))
    print("isInt_re2:   %6.4f" % timeFunc(isInt_re2, 10000))
    print("check_int:   %6.4f" % timeFunc(check_int, 10000))

Here are the performance comparison results:

timings..
isInt_try:   0.6426
isInt_str:   0.7382
isInt_re:    1.1156
isInt_re2:   0.5344
check_int:   0.3452

A C method could scan it Once Through, and be done. A C method that scans the string once through would be the Right Thing to do, I think.

EDIT:

I’ve updated the code above to work in Python 3.5, and to include the check_int function from the currently most voted up answer, and to use the current most popular regex that I can find for testing for integer-hood. This regex rejects strings like ‘abc 123’. I’ve added ‘abc 123’ as a test value.

It is Very Interesting to me to note, at this point, that NONE of the functions tested, including the try method, the popular check_int function, and the most popular regex for testing for integer-hood, return the correct answers for all of the test values (well, depending on what you think the correct answers are; see the test results below).

The built-in int() function silently truncates the fractional part of a floating point number and returns the integer part before the decimal, unless the floating point number is first converted to a string.

The check_int() function returns false for values like 0.0 and 1.0 (which technically are integers) and returns true for values like ’06’.

Here are the current (Python 3.5) test results:

                  isInt_try |       isInt_str       |       isInt_re        |       isInt_re2       |   check_int   |
    0               True    |               True    |               True    |               True    |       True    |
    1               True    |               True    |               True    |               True    |       True    |
    -1              True    |               True    |               True    |               True    |       True    |
    1.0             True    |               True    |               False   |               False   |       False   |
    -1.0            True    |               True    |               False   |               False   |       False   |
    '0'             True    |               True    |               True    |               True    |       True    |
    '0.'            False   |               True    |               False   |               False   |       False   |
    '0.0'           False   |               True    |               False   |               False   |       False   |
    '1'             True    |               True    |               True    |               True    |       True    |
    '-1'            True    |               True    |               True    |               True    |       True    |
    '+1'            True    |               True    |               True    |               True    |       True    |
    '1.0'           False   |               True    |               False   |               False   |       False   |
    '-1.0'          False   |               True    |               False   |               False   |       False   |
    '+1.0'          False   |               True    |               False   |               False   |       False   |
    '06'            True    |               True    |               False   |               False   |       True    |
    'abc 123'       False   |               False   |               False   |               False   |       False   |
    1.1             True    |               False   |               False   |               False   |       False   |
    -1.1            True    |               False   |               False   |               False   |       False   |
    '1.1'           False   |               False   |               False   |               False   |       False   |
    '-1.1'          False   |               False   |               False   |               False   |       False   |
    '+1.1'          False   |               False   |               False   |               False   |       False   |
    '1.1.1'         False   |               False   |               False   |               False   |       False   |
    '1.1.0'         False   |               False   |               False   |               False   |       False   |
    '1.0.1'         False   |               False   |               False   |               False   |       False   |
    '1.0.0'         False   |               False   |               False   |               False   |       False   |
    '1.0.'          False   |               False   |               False   |               False   |       False   |
    '1..0'          False   |               False   |               False   |               False   |       False   |
    '1..'           False   |               False   |               False   |               False   |       False   |
    '0.0.'          False   |               False   |               False   |               False   |       False   |
    '0..0'          False   |               False   |               False   |               False   |       False   |
    '0..'           False   |               False   |               False   |               False   |       False   |
    'one'           False   |               False   |               False   |               False   |       False   |
    <obj..>         False   |               False   |               False   |               False   |       False   |
    (1, 2, 3)       False   |               False   |               False   |               False   |       False   |
    [1, 2, 3]       False   |               False   |               False   |               False   |       False   |
    {'one': 'two'}  False   |               False   |               False   |               False   |       False   |
    ' 0 '           True    |               True    |               True    |               True    |       False   |
    ' 0.'           False   |               True    |               False   |               False   |       False   |
    ' .0'           False   |               False   |               False   |               False   |       False   |
    '.01 '          False   |               False   |               False   |               False   |       False   |

Just now I tried adding this function:

def isInt_float(s):
    try:
        return float(str(s)).is_integer()
    except:
        return False

It performs almost as well as check_int (0.3486) and it returns true for values like 1.0 and 0.0 and +1.0 and 0. and .0 and so on. But it also returns true for ’06’, so. Pick your poison, I guess.


回答 3

str.isdigit() 应该可以。

例子:

str.isdigit("23") ## True
str.isdigit("abc") ## False
str.isdigit("23.4") ## False

编辑:正如@BuzzMoschetti所指出的那样,这种方式将在减号(例如“ -23”)上失败。如果您的input_num可以小于0,请在应用str.isdigit()之前使用re.sub(regex_search,regex_replace,contents 。例如:

import re
input_num = "-23"
input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
str.isdigit(input_num) ## True

str.isdigit() should do the trick.

Examples:

str.isdigit("23") ## True
str.isdigit("abc") ## False
str.isdigit("23.4") ## False

EDIT: As @BuzzMoschetti pointed out, this way will fail for minus number (e.g, “-23”). In case your input_num can be less than 0, use re.sub(regex_search,regex_replace,contents) before applying str.isdigit(). For example:

import re
input_num = "-23"
input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
str.isdigit(input_num) ## True

回答 4

使用正则表达式:

import re
def RepresentsInt(s):
    return re.match(r"[-+]?\d+$", s) is not None

如果还必须接受小数:

def RepresentsInt(s):
    return re.match(r"[-+]?\d+(\.0*)?$", s) is not None

为了提高性能(如果您经常这样做),请仅使用一次编译正则表达式re.compile()

Use a regular expression:

import re
def RepresentsInt(s):
    return re.match(r"[-+]?\d+$", s) is not None

If you must accept decimal fractions also:

def RepresentsInt(s):
    return re.match(r"[-+]?\d+(\.0*)?$", s) is not None

For improved performance if you’re doing this often, compile the regular expression only once using re.compile().


回答 5

适当的RegEx解决方案将结合Greg Hewgill和Nowell的想法,但不使用全局变量。您可以通过将属性附加到方法来完成此操作。另外,我知道将导入放在一种方法中并不容易,但是我要使用的是“惰性模块”效果,例如http://peak.telecommunity.com/DevCenter/Importing#lazy-imports

编辑:到目前为止,我最喜欢的技术是仅使用String对象的方法。

#!/usr/bin/env python

# Uses exclusively methods of the String object
def isInteger(i):
    i = str(i)
    return i=='0' or (i if i.find('..') > -1 else i.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

# Uses re module for regex
def isIntegre(i):
    import re
    if not hasattr(isIntegre, '_re'):
        print("I compile only once. Remove this line when you are confident in that.")
        isIntegre._re = re.compile(r"[-+]?\d+(\.0*)?$")
    return isIntegre._re.match(str(i)) is not None

# When executed directly run Unit Tests
if __name__ == '__main__':
    for obj in [
                # integers
                0, 1, -1, 1.0, -1.0,
                '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0',
                # non-integers
                1.1, -1.1, '1.1', '-1.1', '+1.1',
                '1.1.1', '1.1.0', '1.0.1', '1.0.0',
                '1.0.', '1..0', '1..',
                '0.0.', '0..0', '0..',
                'one', object(), (1,2,3), [1,2,3], {'one':'two'}
            ]:
        # Notice the integre uses 're' (intended to be humorous)
        integer = ('an integer' if isInteger(obj) else 'NOT an integer')
        integre = ('an integre' if isIntegre(obj) else 'NOT an integre')
        # Make strings look like strings in the output
        if isinstance(obj, str):
            obj = ("'%s'" % (obj,))
        print("%30s is %14s is %14s" % (obj, integer, integre))

对于Class较少的成员,输出如下:

I compile only once. Remove this line when you are confident in that.
                             0 is     an integer is     an integre
                             1 is     an integer is     an integre
                            -1 is     an integer is     an integre
                           1.0 is     an integer is     an integre
                          -1.0 is     an integer is     an integre
                           '0' is     an integer is     an integre
                          '0.' is     an integer is     an integre
                         '0.0' is     an integer is     an integre
                           '1' is     an integer is     an integre
                          '-1' is     an integer is     an integre
                          '+1' is     an integer is     an integre
                         '1.0' is     an integer is     an integre
                        '-1.0' is     an integer is     an integre
                        '+1.0' is     an integer is     an integre
                           1.1 is NOT an integer is NOT an integre
                          -1.1 is NOT an integer is NOT an integre
                         '1.1' is NOT an integer is NOT an integre
                        '-1.1' is NOT an integer is NOT an integre
                        '+1.1' is NOT an integer is NOT an integre
                       '1.1.1' is NOT an integer is NOT an integre
                       '1.1.0' is NOT an integer is NOT an integre
                       '1.0.1' is NOT an integer is NOT an integre
                       '1.0.0' is NOT an integer is NOT an integre
                        '1.0.' is NOT an integer is NOT an integre
                        '1..0' is NOT an integer is NOT an integre
                         '1..' is NOT an integer is NOT an integre
                        '0.0.' is NOT an integer is NOT an integre
                        '0..0' is NOT an integer is NOT an integre
                         '0..' is NOT an integer is NOT an integre
                         'one' is NOT an integer is NOT an integre
<object object at 0x103b7d0a0> is NOT an integer is NOT an integre
                     (1, 2, 3) is NOT an integer is NOT an integre
                     [1, 2, 3] is NOT an integer is NOT an integre
                {'one': 'two'} is NOT an integer is NOT an integre

The proper RegEx solution would combine the ideas of Greg Hewgill and Nowell, but not use a global variable. You can accomplish this by attaching an attribute to the method. Also, I know that it is frowned upon to put imports in a method, but what I’m going for is a “lazy module” effect like http://peak.telecommunity.com/DevCenter/Importing#lazy-imports

edit: My favorite technique so far is to use exclusively methods of the String object.

#!/usr/bin/env python

# Uses exclusively methods of the String object
def isInteger(i):
    i = str(i)
    return i=='0' or (i if i.find('..') > -1 else i.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

# Uses re module for regex
def isIntegre(i):
    import re
    if not hasattr(isIntegre, '_re'):
        print("I compile only once. Remove this line when you are confident in that.")
        isIntegre._re = re.compile(r"[-+]?\d+(\.0*)?$")
    return isIntegre._re.match(str(i)) is not None

# When executed directly run Unit Tests
if __name__ == '__main__':
    for obj in [
                # integers
                0, 1, -1, 1.0, -1.0,
                '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0',
                # non-integers
                1.1, -1.1, '1.1', '-1.1', '+1.1',
                '1.1.1', '1.1.0', '1.0.1', '1.0.0',
                '1.0.', '1..0', '1..',
                '0.0.', '0..0', '0..',
                'one', object(), (1,2,3), [1,2,3], {'one':'two'}
            ]:
        # Notice the integre uses 're' (intended to be humorous)
        integer = ('an integer' if isInteger(obj) else 'NOT an integer')
        integre = ('an integre' if isIntegre(obj) else 'NOT an integre')
        # Make strings look like strings in the output
        if isinstance(obj, str):
            obj = ("'%s'" % (obj,))
        print("%30s is %14s is %14s" % (obj, integer, integre))

And for the less adventurous members of the class, here is the output:

I compile only once. Remove this line when you are confident in that.
                             0 is     an integer is     an integre
                             1 is     an integer is     an integre
                            -1 is     an integer is     an integre
                           1.0 is     an integer is     an integre
                          -1.0 is     an integer is     an integre
                           '0' is     an integer is     an integre
                          '0.' is     an integer is     an integre
                         '0.0' is     an integer is     an integre
                           '1' is     an integer is     an integre
                          '-1' is     an integer is     an integre
                          '+1' is     an integer is     an integre
                         '1.0' is     an integer is     an integre
                        '-1.0' is     an integer is     an integre
                        '+1.0' is     an integer is     an integre
                           1.1 is NOT an integer is NOT an integre
                          -1.1 is NOT an integer is NOT an integre
                         '1.1' is NOT an integer is NOT an integre
                        '-1.1' is NOT an integer is NOT an integre
                        '+1.1' is NOT an integer is NOT an integre
                       '1.1.1' is NOT an integer is NOT an integre
                       '1.1.0' is NOT an integer is NOT an integre
                       '1.0.1' is NOT an integer is NOT an integre
                       '1.0.0' is NOT an integer is NOT an integre
                        '1.0.' is NOT an integer is NOT an integre
                        '1..0' is NOT an integer is NOT an integre
                         '1..' is NOT an integer is NOT an integre
                        '0.0.' is NOT an integer is NOT an integre
                        '0..0' is NOT an integer is NOT an integre
                         '0..' is NOT an integer is NOT an integre
                         'one' is NOT an integer is NOT an integre
<object object at 0x103b7d0a0> is NOT an integer is NOT an integre
                     (1, 2, 3) is NOT an integer is NOT an integre
                     [1, 2, 3] is NOT an integer is NOT an integre
                {'one': 'two'} is NOT an integer is NOT an integre

回答 6

>>> "+7".lstrip("-+").isdigit()
True
>>> "-7".lstrip("-+").isdigit()
True
>>> "7".lstrip("-+").isdigit()
True
>>> "13.4".lstrip("-+").isdigit()
False

因此,您的功能将是:

def is_int(val):
   return val[1].isdigit() and val.lstrip("-+").isdigit()
>>> "+7".lstrip("-+").isdigit()
True
>>> "-7".lstrip("-+").isdigit()
True
>>> "7".lstrip("-+").isdigit()
True
>>> "13.4".lstrip("-+").isdigit()
False

So your function would be:

def is_int(val):
   return val[1].isdigit() and val.lstrip("-+").isdigit()

回答 7

Greg Hewgill的方法缺少一些组件:前导“ ^”只匹配字符串的开头,然后预先编译re。但是这种方法将使您避免尝试:专家:

import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
    return INT_RE.match(str(s)) is not None

我很想知道为什么您要尝试避免尝试:除了?

Greg Hewgill’s approach was missing a few components: the leading “^” to only match the start of the string, and compiling the re beforehand. But this approach will allow you to avoid a try: exept:

import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
    return INT_RE.match(str(s)) is not None

I would be interested why you are trying to avoid try: except?


回答 8

我必须一直这样做,而且我对使用try / except模式有轻微但不合理的厌恶感。我用这个:

all([xi in '1234567890' for xi in x])

它不包含负数,因此您可以去除一个减号(如果有),然后检查结果是否包含0-9的数字:

all([xi in '1234567890' for xi in x.replace('-', '', 1)])

如果不确定输入是否为字符串,也可以将x传递给str():

all([xi in '1234567890' for xi in str(x).replace('-', '', 1)])

至少有两种(边缘?)情况会崩溃:

  1. 它不适用于各种科学和/或指数表示法(例如1.2E3、10 ^ 3等)-两者都将返回False。我也不认为其他答案也可以解决这个问题,甚至Python 3.8也有不一致的意见,因为type(1E2)给出了<class 'float'>type(10^2)给出了<class 'int'>
  2. 空字符串输入为True。

因此,它不适用于所有可能的输入,但是如果您可以排除科学计数法,指数计数法和空字符串,则可以单行检查,False如果x不是整数,True并且x是整数,则返回单行检查。

我不知道它是否是pythonic,但这只是一行,而且相对清楚代码的作用。

I have to do this all the time, and I have a mild but admittedly irrational aversion to using the try/except pattern. I use this:

all([xi in '1234567890' for xi in x])

It doesn’t accommodate negative numbers, so you could strip out one minus sign (if any), and then check if the result comprises digits from 0-9:

all([xi in '1234567890' for xi in x.replace('-', '', 1)])

You could also pass x to str() if you’re not sure the input is a string:

all([xi in '1234567890' for xi in str(x).replace('-', '', 1)])

There are at least two (edge?) cases where this falls apart:

  1. It doesn’t work for various scientific and/or exponential notations (e.g. 1.2E3, 10^3, etc.) – both will return False. I don’t think other answers accommodated this either, and even Python 3.8 has inconsistent opinions, since type(1E2) gives <class 'float'> whereas type(10^2) gives <class 'int'>.
  2. An empty string input gives True.

So it won’t work for every possible input, but if you can exclude scientific notation, exponential notation, and empty strings, it’s an OK one-line check that returns False if x is not an integer and True if x is an integer.

I don’t know if it’s pythonic, but it’s one line, and it’s relatively clear what the code does.


回答 9

我认为

s.startswith('-') and s[1:].isdigit()

最好重写为:

s.replace('-', '').isdigit()

因为s [1:]也创建了一个新字符串

但是更好的解决方案是

s.lstrip('+-').isdigit()

I think

s.startswith('-') and s[1:].isdigit()

would be better to rewrite to:

s.replace('-', '').isdigit()

because s[1:] also creates a new string

But much better solution is

s.lstrip('+-').isdigit()

回答 10

我真的很喜欢Shavais的帖子,但是我又添加了一个测试用例(和内置的isdigit()函数):

def isInt_loop(v):
    v = str(v).strip()
    # swapping '0123456789' for '9876543210' makes nominal difference (might have because '1' is toward the beginning of the string)
    numbers = '0123456789'
    for i in v:
        if i not in numbers:
            return False
    return True

def isInt_Digit(v):
    v = str(v).strip()
    return v.isdigit()

并且始终如一地超越其他时间:

timings..
isInt_try:   0.4628
isInt_str:   0.3556
isInt_re:    0.4889
isInt_re2:   0.2726
isInt_loop:   0.1842
isInt_Digit:   0.1577

使用普通的2.7 python:

$ python --version
Python 2.7.10

我添加的两个测试用例(isInt_loop和isInt_digit)都通过了完全相同的测试用例(它们都只接受无符号整数),但是我认为人们可以更灵活地修改字符串实现(isInt_loop),而不是内置的isdigit ()函数,因此即使执行时间略有不同,我也将其包含在内。(而且这两种方法都击败了其他一切,但是不处理多余的东西:“ ./+/-”)

此外,我确实发现有趣的是注意到正则表达式(isInt_re2方法)在Shavais于2012年(当前为2018年)执行的同一测试中击败了字符串比较。也许正则表达式库得到了改进?

I really liked Shavais’ post, but I added one more test case ( & the built in isdigit() function):

def isInt_loop(v):
    v = str(v).strip()
    # swapping '0123456789' for '9876543210' makes nominal difference (might have because '1' is toward the beginning of the string)
    numbers = '0123456789'
    for i in v:
        if i not in numbers:
            return False
    return True

def isInt_Digit(v):
    v = str(v).strip()
    return v.isdigit()

and it significantly consistently beats the times of the rest:

timings..
isInt_try:   0.4628
isInt_str:   0.3556
isInt_re:    0.4889
isInt_re2:   0.2726
isInt_loop:   0.1842
isInt_Digit:   0.1577

using normal 2.7 python:

$ python --version
Python 2.7.10

Both the two test cases I added (isInt_loop and isInt_digit) pass the exact same test cases (they both only accept unsigned integers), but I thought that people could be more clever with modifying the string implementation (isInt_loop) opposed to the built in isdigit() function, so I included it, even though there’s a slight difference in execution time. (and both methods beat everything else by a lot, but don’t handle the extra stuff: “./+/-” )

Also, I did find it interesting to note that the regex (isInt_re2 method) beat the string comparison in the same test that was performed by Shavais in 2012 (currently 2018). Maybe the regex libraries have been improved?


回答 11

在我看来,这可能是最直接,最Python的方法。我没有看到这种解决方案,它与regex基本相同,但是没有regex。

def is_int(test):
    import string
    return not (set(test) - set(string.digits))

This is probably the most straightforward and pythonic way to approach it in my opinion. I didn’t see this solution and it’s basically the same as the regex one, but without the regex.

def is_int(test):
    import string
    return not (set(test) - set(string.digits))

回答 12

这是一个不会引起错误的解析函数。它处理明显的None失败案例(在CPython上默认处理多达2000个“-/ +”符号!):

#!/usr/bin/env python

def get_int(number):
    splits = number.split('.')
    if len(splits) > 2:
        # too many splits
        return None
    if len(splits) == 2 and splits[1]:
        # handle decimal part recursively :-)
        if get_int(splits[1]) != 0:
            return None

    int_part = splits[0].lstrip("+")
    if int_part.startswith('-'):
        # handle minus sign recursively :-)
        return get_int(int_part[1:]) * -1
    # successful 'and' returns last truth-y value (cast is always valid)
    return int_part.isdigit() and int(int_part)

一些测试:

tests = ["0", "0.0", "0.1", "1", "1.1", "1.0", "-1", "-1.1", "-1.0", "-0", "--0", "---3", '.3', '--3.', "+13", "+-1.00", "--+123", "-0.000"]

for t in tests:
    print "get_int(%s) = %s" % (t, get_int(str(t)))

结果:

get_int(0) = 0
get_int(0.0) = 0
get_int(0.1) = None
get_int(1) = 1
get_int(1.1) = None
get_int(1.0) = 1
get_int(-1) = -1
get_int(-1.1) = None
get_int(-1.0) = -1
get_int(-0) = 0
get_int(--0) = 0
get_int(---3) = -3
get_int(.3) = None
get_int(--3.) = 3
get_int(+13) = 13
get_int(+-1.00) = -1
get_int(--+123) = 123
get_int(-0.000) = 0

根据您的需要,您可以使用:

def int_predicate(number):
     return get_int(number) is not None

Here is a function that parses without raising errors. It handles obvious cases returns None on failure (handles up to 2000 ‘-/+’ signs by default on CPython!):

#!/usr/bin/env python

def get_int(number):
    splits = number.split('.')
    if len(splits) > 2:
        # too many splits
        return None
    if len(splits) == 2 and splits[1]:
        # handle decimal part recursively :-)
        if get_int(splits[1]) != 0:
            return None

    int_part = splits[0].lstrip("+")
    if int_part.startswith('-'):
        # handle minus sign recursively :-)
        return get_int(int_part[1:]) * -1
    # successful 'and' returns last truth-y value (cast is always valid)
    return int_part.isdigit() and int(int_part)

Some tests:

tests = ["0", "0.0", "0.1", "1", "1.1", "1.0", "-1", "-1.1", "-1.0", "-0", "--0", "---3", '.3', '--3.', "+13", "+-1.00", "--+123", "-0.000"]

for t in tests:
    print "get_int(%s) = %s" % (t, get_int(str(t)))

Results:

get_int(0) = 0
get_int(0.0) = 0
get_int(0.1) = None
get_int(1) = 1
get_int(1.1) = None
get_int(1.0) = 1
get_int(-1) = -1
get_int(-1.1) = None
get_int(-1.0) = -1
get_int(-0) = 0
get_int(--0) = 0
get_int(---3) = -3
get_int(.3) = None
get_int(--3.) = 3
get_int(+13) = 13
get_int(+-1.00) = -1
get_int(--+123) = 123
get_int(-0.000) = 0

For your needs you can use:

def int_predicate(number):
     return get_int(number) is not None

回答 13

我建议以下内容:

import ast

def is_int(s):
    return isinstance(ast.literal_eval(s), int)

文档

安全地评估表达式节点或包含Python文字或容器显示的字符串。提供的字符串或节点只能由以下Python文字结构组成:字符串,字节,数字,元组,列表,字典,集合,布尔值和无。

我应该注意,ValueError当对任何不构成Python文字的内容进行调用时,这将引发异常。由于问题要求的解决方案没有try / except,因此我为此准备了Kobayashi-Maru类型的解决方案:

from ast import literal_eval
from contextlib import suppress

def is_int(s):
    with suppress(ValueError):
        return isinstance(literal_eval(s), int)
    return False

¯\ _(ツ)_ /¯

I suggest the following:

import ast

def is_int(s):
    return isinstance(ast.literal_eval(s), int)

From the docs:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

I should note that this will raise a ValueError exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:

from ast import literal_eval
from contextlib import suppress

def is_int(s):
    with suppress(ValueError):
        return isinstance(literal_eval(s), int)
    return False

¯\_(ツ)_/¯


回答 14

我有一种根本不使用int的可能性,并且除非字符串不代表数字,否则不应引发异常

float(number)==float(number)//1

它应该适用于float接受的任何类型的字符串(正,负,工程符号)。

I have one possibility that doesn’t use int at all, and should not raise an exception unless the string does not represent a number

float(number)==float(number)//1

It should work for any kind of string that float accepts, positive, negative, engineering notation…


回答 15

我猜这个问题与速度有关,因为try / except有时间限制:

 测试数据

首先,我创建了一个包含200个字符串,100个失败字符串和100个数字字符串的列表。

from random import shuffle
numbers = [u'+1'] * 100
nonumbers = [u'1abc'] * 100
testlist = numbers + nonumbers
shuffle(testlist)
testlist = np.array(testlist)

 numpy解决方案(仅适用于数组和unicode)

np.core.defchararray.isnumeric也可以使用unicode字符串,np.core.defchararray.isnumeric(u'+12')但是它返回和数组。因此,如果您必须进行数千次转换并且缺少数据或非数字数据,这是一个很好的解决方案。

import numpy as np
%timeit np.core.defchararray.isnumeric(testlist)
10000 loops, best of 3: 27.9 µs per loop # 200 numbers per loop

尝试/除外

def check_num(s):
  try:
    int(s)
    return True
  except:
    return False

def check_list(l):
  return [check_num(e) for e in l]

%timeit check_list(testlist)
1000 loops, best of 3: 217 µs per loop # 200 numbers per loop

似乎numpy解决方案要快得多。

I guess the question is related with speed since the try/except has a time penalty:

 test data

First, I created a list of 200 strings, 100 failing strings and 100 numeric strings.

from random import shuffle
numbers = [u'+1'] * 100
nonumbers = [u'1abc'] * 100
testlist = numbers + nonumbers
shuffle(testlist)
testlist = np.array(testlist)

 numpy solution (only works with arrays and unicode)

np.core.defchararray.isnumeric can also work with unicode strings np.core.defchararray.isnumeric(u'+12') but it returns and array. So, it’s a good solution if you have to do thousands of conversions and have missing data or non numeric data.

import numpy as np
%timeit np.core.defchararray.isnumeric(testlist)
10000 loops, best of 3: 27.9 µs per loop # 200 numbers per loop

try/except

def check_num(s):
  try:
    int(s)
    return True
  except:
    return False

def check_list(l):
  return [check_num(e) for e in l]

%timeit check_list(testlist)
1000 loops, best of 3: 217 µs per loop # 200 numbers per loop

Seems that numpy solution is much faster.


回答 16

如果您只想接受低位数字,请执行以下测试:

Python 3.7+: (u.isdecimal() and u.isascii())

Python <= 3.6: (u.isdecimal() and u == str(int(u)))

其他答案建议使用.isdigit()或,.isdecimal()都包含一些高位unicode字符,例如'٢'u'\u0662'):

u = u'\u0662'     # '٢'
u.isdigit()       # True
u.isdecimal()     # True
u.isascii()       # False (Python 3.7+ only)
u == str(int(u))  # False

If you want to accept lower-ascii digits only, here are tests to do so:

Python 3.7+: (u.isdecimal() and u.isascii())

Python <= 3.6: (u.isdecimal() and u == str(int(u)))

Other answers suggest using .isdigit() or .isdecimal() but these both include some upper-unicode characters such as '٢' (u'\u0662'):

u = u'\u0662'     # '٢'
u.isdigit()       # True
u.isdecimal()     # True
u.isascii()       # False (Python 3.7+ only)
u == str(int(u))  # False

回答 17

嗯。尝试这个:

def int_check(a):
    if int(a) == a:
        return True
    else:
        return False

如果您不输入不是数字的字符串,则此方法有效。

而且(我忘了放数字检查部分。),还有一个函数检查字符串是否是数字。它是str.isdigit()。这是一个例子:

a = 2
a.isdigit()

如果调用a.isdigit(),它将返回True。

Uh.. Try this:

def int_check(a):
    if int(a) == a:
        return True
    else:
        return False

This works if you don’t put a string that’s not a number.

And also (I forgot to put the number check part. ), there is a function checking if the string is a number or not. It is str.isdigit(). Here’s an example:

a = 2
a.isdigit()

If you call a.isdigit(), it will return True.


如何在Python中将字符串转换为整数?

问题:如何在Python中将字符串转换为整数?

我有一个来自MySQL查询的元组,像这样:

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))

我想将所有字符串元素转换为整数,然后将它们放回列表列表中:

T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

我试图用它来实现它,eval但是还没有得到令人满意的结果。

I have a tuple of tuples from a MySQL query like this:

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))

I’d like to convert all the string elements into integers and put them back into a list of lists:

T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

I tried to achieve it with eval but didn’t get any decent result yet.


回答 0

int()是Python标准的内置函数,用于将字符串转换为整数值。您使用一个包含数字作为参数的字符串来调用它,它返回转换为整数的数字:

print (int("1") + 1)

上面的照片2

如果您知道列表T1的结构(它仅包含列表,仅一个级别),则可以在Python 2中执行此操作:

T2 = [map(int, x) for x in T1]

在Python 3中:

T2 = [list(map(int, x)) for x in T1]

int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:

print (int("1") + 1)

The above prints 2.

If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 2:

T2 = [map(int, x) for x in T1]

In Python 3:

T2 = [list(map(int, x)) for x in T1]

回答 1

您可以通过列表理解来做到这一点:

T2 = [[int(column) for column in row] for row in T1]

内部列表理解([int(column) for column in row])建立一个listint期从序列int-able物体,如小数字符串中row。外部列表推导([... for row in T1]))生成一个内部列表推导的结果的列表,该结果适用于中的每个项目T1

如果任何行包含无法通过转换的对象,则代码段将失败int。如果要处理包含非十进制字符串的行,则需要一个更智能的函数。

如果您知道行的结构,则可以使用对行函数的调用来替换内部列表理解。例如。

T2 = [parse_a_row_of_T1(row) for row in T1]

You can do this with a list comprehension:

T2 = [[int(column) for column in row] for row in T1]

The inner list comprehension ([int(column) for column in row]) builds a list of ints from a sequence of int-able objects, like decimal strings, in row. The outer list comprehension ([... for row in T1])) builds a list of the results of the inner list comprehension applied to each item in T1.

The code snippet will fail if any of the rows contain objects that can’t be converted by int. You’ll need a smarter function if you want to process rows containing non-decimal strings.

If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.

T2 = [parse_a_row_of_T1(row) for row in T1]

回答 2

我宁愿只使用理解列表:

[[int(y) for y in x] for x in T1]

I would rather prefer using only comprehension lists:

[[int(y) for y in x] for x in T1]

回答 3

代替put int( ),put float( )可以让您将小数与整数一起使用。

Instead of putting int( ), put float( ) which will let you use decimals along with integers.


回答 4

到目前为止,我都同意所有人的回答,但是问题是,如果您没有所有整数,它们将崩溃。

如果要排除非整数,则

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))
new_list = list(list(int(a) for a in b) for b in T1 if a.isdigit())

这仅产生实际数字。我不使用直接列表推导的原因是因为列表推导会泄漏其内部变量。

I would agree with everyones answers so far but the problem is is that if you do not have all integers they will crash.

If you wanted to exclude non-integers then

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))
new_list = list(list(int(a) for a in b) for b in T1 if a.isdigit())

This yields only actual digits. The reason I don’t use direct list comprehensions is because list comprehension leaks their internal variables.


回答 5

T3=[]

for i in range(0,len(T1)):
    T3.append([])
    for j in range(0,len(T1[i])):
        b=int(T1[i][j])
        T3[i].append(b)

print T3
T3=[]

for i in range(0,len(T1)):
    T3.append([])
    for j in range(0,len(T1[i])):
        b=int(T1[i][j])
        T3[i].append(b)

print T3

回答 6

尝试这个。

x = "1"

x是一个字符串,因为它周围带有引号,但其中带有数字。

x = int(x)

由于x的数字为1,因此我可以将其变成整数。

要查看字符串是否为数字,可以执行此操作。

def is_number(var):
    try:
        if var == int(var):
            return True
    except Exception:
        return False

x = "1"

y = "test"

x_test = is_number(x)

print(x_test)

它应该打印到IDLE True,因为x是一个数字。

y_test = is_number(y)

print(y_test)

它应该打印为IDLE False,因为y中没有数字。

Try this.

x = "1"

x is a string because it has quotes around it, but it has a number in it.

x = int(x)

Since x has the number 1 in it, I can turn it in to a integer.

To see if a string is a number, you can do this.

def is_number(var):
    try:
        if var == int(var):
            return True
    except Exception:
        return False

x = "1"

y = "test"

x_test = is_number(x)

print(x_test)

It should print to IDLE True because x is a number.

y_test = is_number(y)

print(y_test)

It should print to IDLE False because y in not a number.


回答 7

使用列表推导:

t2 = [map(int, list(l)) for l in t1]

Using list comprehensions:

t2 = [map(int, list(l)) for l in t1]

回答 8

在Python 3.5.1中,这些工作如下:

c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))

Enter number:  4.7
4
5

乔治。

In Python 3.5.1 things like these work:

c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))

and

Enter number:  4.7
4
5

George.


回答 9

查看此功能

def parse_int(s):
    try:
        res = int(eval(str(s)))
        if type(res) == int:
            return res
    except:
        return

然后

val = parse_int('10')  # Return 10
val = parse_int('0')  # Return 0
val = parse_int('10.5')  # Return 10
val = parse_int('0.0')  # Return 0
val = parse_int('Ten')  # Return None

您也可以检查

if val == None:  # True if input value can not be converted
    pass  # Note: Don't use 'if not val:'

See this function

def parse_int(s):
    try:
        res = int(eval(str(s)))
        if type(res) == int:
            return res
    except:
        return

Then

val = parse_int('10')  # Return 10
val = parse_int('0')  # Return 0
val = parse_int('10.5')  # Return 10
val = parse_int('0.0')  # Return 0
val = parse_int('Ten')  # Return None

You can also check

if val == None:  # True if input value can not be converted
    pass  # Note: Don't use 'if not val:'

回答 10

适用于Python 2的另一个功能解决方案:

from functools import partial

map(partial(map, int), T1)

不过,Python 3会有些混乱:

list(map(list, map(partial(map, int), T1)))

我们可以用包装纸解决

def oldmap(f, iterable):
    return list(map(f, iterable))

oldmap(partial(oldmap, int), T1)

Yet another functional solution for Python 2:

from functools import partial

map(partial(map, int), T1)

Python 3 will be a little bit messy though:

list(map(list, map(partial(map, int), T1)))

we can fix this with a wrapper

def oldmap(f, iterable):
    return list(map(f, iterable))

oldmap(partial(oldmap, int), T1)

回答 11

如果只是元组的元组,类似 rows=[map(int, row) for row in rows]就可以解决。(在其中有一个列表推导和对map(f,lst)的调用,该调用等于[f in a lst]中的f(a)。)

如果由于某种原因在数据库中有类似的东西,Eval 不是您想要做的__import__("os").unlink("importantsystemfile")。始终验证您的输入(如果没有其他问题,如果输入错误,则会引发int()异常)。

If it’s only a tuple of tuples, something like rows=[map(int, row) for row in rows] will do the trick. (There’s a list comprehension and a call to map(f, lst), which is equal to [f(a) for a in lst], in there.)

Eval is not what you want to do, in case there’s something like __import__("os").unlink("importantsystemfile") in your database for some reason. Always validate your input (if with nothing else, the exception int() will raise if you have bad input).


回答 12

您可以执行以下操作:

T1 = (('13', '17', '18', '21', '32'),  
     ('07', '11', '13', '14', '28'),  
     ('01', '05', '06', '08', '15', '16'))  
new_list = list(list(int(a) for a in b if a.isdigit()) for b in T1)  
print(new_list)  

You can do something like this:

T1 = (('13', '17', '18', '21', '32'),  
     ('07', '11', '13', '14', '28'),  
     ('01', '05', '06', '08', '15', '16'))  
new_list = list(list(int(a) for a in b if a.isdigit()) for b in T1)  
print(new_list)  

回答 13

我想分享一个似乎此处未提及的可用选项:

rumpy.random.permutation(x)

将生成数组x的随机排列。不完全是您的要求,但这是解决类似问题的潜在方法。

I want to share an available option that doesn’t seem to be mentioned here yet:

rumpy.random.permutation(x)

Will generate a random permutation of array x. Not exactly what you asked for, but it is a potential solution to similar questions.


显示数字的前导零

问题:显示数字的前导零

鉴于:

a = 1
b = 10
c = 100

如何为少于两位的所有数字显示前导零?

这是我期望的输出:

01
10
100

Given:

a = 1
b = 10
c = 100

How do I display a leading zero for all numbers with less than two digits?

This is the output I’m expecting:

01
10
100

回答 0

在Python 2(和Python 3)中,您可以执行以下操作:

print "%02d" % (1,)

基本上就像printfsprintf(请参阅docs)。


对于Python 3. +,也可以通过以下方式实现相同的行为format

print("{:02d}".format(1))

对于Python 3.6+,可以使用f-strings实现相同的行为:

print(f"{1:02d}")

In Python 2 (and Python 3) you can do:

print "%02d" % (1,)

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

print("{:02d}".format(1))

For Python 3.6+ the same behavior can be achieved with f-strings:

print(f"{1:02d}")

回答 1

您可以使用str.zfill

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

印刷品:

01
10
100

You can use str.zfill:

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

prints:

01
10
100

回答 2

在Python 2.6+和3.0+中,您将使用format()字符串方法:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

或使用内置的(对于单个数字):

print(format(i, '02d'))

有关新的格式化功能,请参阅PEP-3101文档。

In Python 2.6+ and 3.0+, you would use the format() string method:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

or using the built-in (for a single number):

print(format(i, '02d'))

See the PEP-3101 documentation for the new formatting functions.


回答 3

print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

印刷品:

01
10
100
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

prints:

01
10
100

回答 4

或这个:

print '{0:02d}'.format(1)

Or this:

print '{0:02d}'.format(1)


回答 5

Python> = 3.6中,您可以使用以下命令引入的新f字符串来简洁地执行此操作:

f'{val:02}'

它打印用名称的变量val具有fill的值0width2

对于您的特定示例,您可以在循环中很好地做到这一点:

a, b, c = 1, 10, 100
for val in [a, b, c]:
    print(f'{val:02}')

打印:

01 
10
100

有关f弦的更多信息,请查看引入它们的PEP 498

In Python >= 3.6, you can do this succinctly with the new f-strings that were introduced by using:

f'{val:02}'

which prints the variable with name val with a fill value of 0 and a width of 2.

For your specific example you can do this nicely in a loop:

a, b, c = 1, 10, 100
for val in [a, b, c]:
    print(f'{val:02}')

which prints:

01 
10
100

For more information on f-strings, take a look at PEP 498 where they were introduced.


回答 6

x = [1, 10, 100]
for i in x:
    print '%02d' % i

结果是:

01
10
100

在文档中阅读有关使用%格式化字符串的更多信息

x = [1, 10, 100]
for i in x:
    print '%02d' % i

results in:

01
10
100

Read more information about string formatting using % in the documentation.


回答 7

使用Python的方式:

str(number).rjust(string_width, fill_char)

这样,如果原始字符串的长度大于string_width,则将其原样返回。例:

a = [1, 10, 100]
for num in a:
    print str(num).rjust(2, '0')

结果:

01
10
100

The Pythonic way to do this:

str(number).rjust(string_width, fill_char)

This way, the original string is returned unchanged if its length is greater than string_width. Example:

a = [1, 10, 100]
for num in a:
    print str(num).rjust(2, '0')

Results:

01
10
100

回答 8

或其他解决方案。

"{:0>2}".format(number)

Or another solution.

"{:0>2}".format(number)

回答 9

使用格式字符串-http://docs.python.org/lib/typesseq-strings.html

例如:

python -c 'print "%(num)02d" % {"num":5}'

Use a format string – http://docs.python.org/lib/typesseq-strings.html

For example:

python -c 'print "%(num)02d" % {"num":5}'

回答 10

这是我的方法:

str(1).zfill(len(str(total)))

基本上,zfill接受要添加的前导零的数量,因此很容易将最大的数字转换为字符串并获取长度,如下所示:

Python 3.6.5(默认,2018年5月11日,04:00:52) 
Linux上的[GCC 8.1.0]
键入“帮助”,“版权”,“信用”或“许可证”以获取更多信息。
>>>总计= 100
>>>打印(str(1).zfill(len(str(total))))
001
>>>总计= 1000
>>>打印(str(1).zfill(len(str(total))))
0001
>>>总计= 10000
>>>打印(str(1).zfill(len(str(total))))
00001
>>> 

This is how I do it:

str(1).zfill(len(str(total)))

Basically zfill takes the number of leading zeros you want to add, so it’s easy to take the biggest number, turn it into a string and get the length, like this:

Python 3.6.5 (default, May 11 2018, 04:00:52) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>> 

回答 11

width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted

回答 12

您可以使用f字符串执行此操作

import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

这将打印恒定长度的8,并用领先的填充0

00000001
00000124
00013566

You can do this with f strings.

import numpy as np

print(f'{np.random.choice([1, 124, 13566]):0>8}')

This will print constant length of 8, and pad the rest with leading 0.

00000001
00000124
00013566

回答 13

采用:

'00'[len(str(i)):] + str(i)

或与math模块:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)

Use:

'00'[len(str(i)):] + str(i)

Or with the math module:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)

回答 14

df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))

5是总位数。

我使用了以下链接:http : //www.datasciencemadesimple.com/add-leading-preceding-zeros-python/

df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))

The 5 is the number of total digits.

I used this link: http://www.datasciencemadesimple.com/add-leading-preceding-zeros-python/


回答 15

如果处理的是一位或两位数字:

'0'+str(number)[-2:] 要么 '0{0}'.format(number)[-2:]

If dealing with numbers that are either one or two digits:

'0'+str(number)[-2:] or '0{0}'.format(number)[-2:]


整数的最大值和最小值

问题:整数的最大值和最小值

我正在寻找python中整数的最小值和最大值。例如,在Java中,我们有Integer.MIN_VALUEInteger.MAX_VALUE。python中是否有类似的东西?

I am looking for minimum and maximum values for integers in python. For eg., in Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE. Is there something like this in python?


回答 0

Python 3

在Python 3中,此问题不适用。普通int类型是无界的。

但是,您实际上可能正在寻找有关当前解释器的字长的信息,在大多数情况下,该信息将与机器的字长相同。该信息仍在Python 3中以形式提供sys.maxsize,这是一个有符号的单词可以表示的最大值。等效地,它是最大可能列表或内存序列的大小

通常,无符号字可表示的最大值为,字中sys.maxsize * 2 + 1的位数为math.log2(sys.maxsize * 2 + 2)。有关更多信息,请参见此答案

Python 2

在Python 2中,纯int值的最大值可作为sys.maxint

>>> sys.maxint
9223372036854775807

你可以计算与最小值-sys.maxint - 1如图所示这里

一旦超过此值,Python就会从纯整数无缝转换为长整数。因此,大多数时候,您不需要了解它。

Python 3

In Python 3, this question doesn’t apply. The plain int type is unbounded.

However, you might actually be looking for information about the current interpreter’s word size, which will be the same as the machine’s word size in most cases. That information is still available in Python 3 as sys.maxsize, which is the maximum value representable by a signed word. Equivalently, it’s the size of the largest possible list or in-memory sequence.

Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1, and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2). See this answer for more information.

Python 2

In Python 2, the maximum value for plain int values is available as sys.maxint:

>>> sys.maxint
9223372036854775807

You can calculate the minimum value with -sys.maxint - 1 as shown here.

Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won’t need to know it.


回答 1

如果您只需要一个大于所有其他数字的数字,则可以使用

float('inf')

以类似的方式,比所有其他方法小:

float('-inf')

这适用于python 2和3。

If you just need a number that’s bigger than all others, you can use

float('inf')

in similar fashion, a number smaller than all others:

float('-inf')

This works in both python 2 and 3.


回答 2

sys.maxint常数已经在Python 3.0取出以后,改为使用sys.maxsize

整数

  • PEP 237:从本质上讲,long已重命名为int。也就是说,只有一个内置的整数类型,称为int;但它的行为基本上类似于旧的long类型。
  • PEP 238:类似1/2的表达式返回浮点数。使用1 // 2获得截断行为。(至少从Python 2.2开始,后一种语法已经存在多年了。)
  • sys.maxint常量已删除,因为整数值不再受限制。但是,sys.maxsize可以用作大于任何实际列表或字符串索引的整数。它符合实现的“自然”整数大小,并且通常与同一平台上的先前版本中的sys.maxint相同(假定具有相同的生成选项)。
  • 长整数的repr()不再包含结尾的L,因此无条件剥离该字符的代码将砍掉最后一位数字。(改为使用str()。)
  • 八进制文字不再采用0720的形式;请改用0o720。

参考:https : //docs.python.org/3/whatsnew/3.0.html#integers

The sys.maxint constant has been removed from Python 3.0 onward, instead use sys.maxsize.

Integers

  • PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.
  • PEP 238: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)
  • The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
  • The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally strips that character will chop off the last digit instead. (Use str() instead.)
  • Octal literals are no longer of the form 0720; use 0o720 instead.

Refer : https://docs.python.org/3/whatsnew/3.0.html#integers


回答 3

在Python中,一旦您传递值,整数将自动从固定大小的int表示形式转换为宽度可变的long表示形式,该值取决于平台sys.maxint是2 311-1或2 63-1。请注意L,此处已附加:

>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L

Python手册

数字是通过数字文字或内置函数和运算符创建的。未经修饰的整数文字(包括二进制,十六进制和八进制数字)将生成纯整数,除非它们表示的值太大而无法表示为纯整数,在这种情况下,它们将生成一个长整数。带'L''l'后缀的整数文字产生长整数('L'首选,因为1l看起来太像11!)。

Python非常努力地假装其整数是数学整数并且是无界的。例如,它可以轻松计算出googol

>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

In Python integers will automatically switch from a fixed-size int representation into a variable width long representation once you pass the value sys.maxint, which is either 231 – 1 or 263 – 1 depending on your platform. Notice the L that gets appended here:

>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L

From the Python manual:

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an 'L' or 'l' suffix yield long integers ('L' is preferred because 1l looks too much like eleven!).

Python tries very hard to pretend its integers are mathematical integers and are unbounded. It can, for instance, calculate a googol with ease:

>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

回答 4

对于Python 3,它是

import sys
max = sys.maxsize
min = -sys.maxsize - 1

For Python 3, it is

import sys
max = sys.maxsize
min = -sys.maxsize - 1

回答 5

您可以这样使用’inf’:

import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf

请参阅:数学—数学函数

You may use ‘inf’ like this:

import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf

Refer: math — Mathematical functions


回答 6

如果您想要数组或列表索引的最大值(相当于size_tC / C ++),则可以使用numpy:

np.iinfo(np.intp).max

这是相同的,sys.maxsize但是优点是您不需要为此仅导入sys。

如果要在计算机上将max用于本机int:

np.iinfo(np.intc).max

您可以在doc中查看其他可用类型。

对于float,您也可以使用sys.float_info.max

If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:

np.iinfo(np.intp).max

This is same as sys.maxsize however advantage is that you don’t need import sys just for this.

If you want max for native int on the machine:

np.iinfo(np.intc).max

You can look at other available types in doc.

For floats you can also use sys.float_info.max.


回答 7

我严重依赖这样的命令。

python -c 'import sys; print(sys.maxsize)'

返回的最大整数:9223372036854775807

有关“ sys”的更多参考,请访问

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize

I rely heavily on commands like this.

python -c 'import sys; print(sys.maxsize)'

Max int returned: 9223372036854775807

For more references for ‘sys’ you should access

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize


如何强制除法为浮点数?除数一直舍入到0?

问题:如何强制除法为浮点数?除数一直舍入到0?

我有两个整数值ab,但是我需要它们在浮点数中的比率。我知道a < b并且想要计算a / b,所以如果我使用整数除法,我将总是得到0,余数为a

c在下文中,如何在Python中强制成为浮点数?

c = a / b

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I’ll always get 0 with a remainder of a.

How can I force c to be a floating point number in Python in the following?

c = a / b

回答 0

在Python 2中,两个整数的除法产生一个整数。在Python 3中,它产生一个浮点数。我们可以通过从中导入来获得新的行为__future__

>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663

In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.

>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663

回答 1

您可以通过执行此操作来浮动c = a / float(b)。如果分子或分母是浮点数,则结果也将是。


一个警告:如评论员所指出的,如果b它不是整数或浮点数(或表示一个的字符串),则此方法将无效。如果您正在处理其他类型(例如复数),则需要检查这些类型或使用其他方法。

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won’t work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you’ll need to either check for those or use a different method.


回答 2

如何在Python中强制除法为浮点数?

我有两个整数值a和b,但是我需要它们在浮点数中的比率。我知道a <b并且我想计算a / b,所以如果我使用整数除法,我总是得到0并得到a的余数。

下面如何在Python中强制c为浮点数?

c = a / b

这里真正要问的是:

“我如何强制进行真正的除法以a / b返回分数?”

升级到Python 3

在Python 3中,要进行真正的除法,只需执行a / b

>>> 1/2
0.5

地板除法(整数的经典除法行为)现在为a // b

>>> 1//2
0
>>> 1//2.0
0.0

但是,您可能无法使用Python 2,或者编写的代码必须能同时在2和3中使用。

如果使用Python 2

在Python 2中,它不是那么简单。处理经典Python 2分区的某些方法比其他方法更好,更可靠。

对Python 2的建议

您可以在任何给定的模块中获得Python 3划分行为,并在顶部输入以下内容:

from __future__ import division

然后将Python 3样式划分应用于整个模块。它也可以在任何给定的点在python shell中工作。在Python 2中:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0

这确实是最好的解决方案,因为它可以确保模块中的代码与Python 3向前兼容。

Python 2的其他选项

如果您不想将其应用于整个模块,则只能使用一些解决方法。最受欢迎的是将其中一个操作数强制为浮点数。一种可靠的解决方案是a / (b * 1.0)。在新的Python Shell中:

>>> 1/(2 * 1.0)
0.5

truediv来自operator模块operator.truediv(a, b)的功能也很强大,但这可能会更慢,因为它是一个函数调用:

>>> from operator import truediv
>>> truediv(1, 2)
0.5

不建议用于Python 2

常见的是a / float(b)。如果b为复数,则将引发TypeError。由于定义了带有复数的除法,所以对我来说,在为除数传递一个复数时,除法不会失败。

>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

对我而言,故意使您的代码更脆弱没有太大意义。

您也可以使用-Qnew标记运行Python ,但这不利于执行具有新Python 3行为的所有模块,并且您的某些模块可能需要经典的划分,因此除测试外,我不建议这样做。但要演示:

$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j

How can I force division to be floating point in Python?

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I’ll always get 0 with a remainder of a.

How can I force c to be a floating point number in Python in the following?

c = a / b

What is really being asked here is:

“How do I force true division such that a / b will return a fraction?”

Upgrade to Python 3

In Python 3, to get true division, you simply do a / b.

>>> 1/2
0.5

Floor division, the classic division behavior for integers, is now a // b:

>>> 1//2
0
>>> 1//2.0
0.0

However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.

If Using Python 2

In Python 2, it’s not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.

Recommendation for Python 2

You can get Python 3 division behavior in any given module with the following import at the top:

from __future__ import division

which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0

This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.

Other Options for Python 2

If you don’t want to apply this to the entire module, you’re limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:

>>> 1/(2 * 1.0)
0.5

Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it’s a function call:

>>> from operator import truediv
>>> truediv(1, 2)
0.5

Not Recommended for Python 2

Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.

>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

It doesn’t make much sense to me to purposefully make your code more brittle.

You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don’t recommend this except for testing. But to demonstrate:

$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j

回答 3

c = a / (b * 1.0)
c = a / (b * 1.0)

回答 4

在Python 3.x中,单斜杠(/)始终表示真实(非截断)除法。(//运算符用于截断除法。)在Python 2.x(2.2及更高版本)中,您可以通过将

from __future__ import division

在模块顶部。

In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a

from __future__ import division

at the top of your module.


回答 5

仅以浮点格式进行除法的任何参数也会产生浮点输出。

例:

>>> 4.0/3
1.3333333333333333

要么,

>>> 4 / 3.0
1.3333333333333333

要么,

>>> 4 / float(3)
1.3333333333333333

要么,

>>> float(4) / 3
1.3333333333333333

Just making any of the parameters for division in floating-point format also produces the output in floating-point.

Example:

>>> 4.0/3
1.3333333333333333

or,

>>> 4 / 3.0
1.3333333333333333

or,

>>> 4 / float(3)
1.3333333333333333

or,

>>> float(4) / 3
1.3333333333333333

回答 6

加一个点(.)表示浮点数

>>> 4/3.
1.3333333333333333

Add a dot (.) to indicate floating point numbers

>>> 4/3.
1.3333333333333333

回答 7

这也可以

>>> u=1./5
>>> print u
0.2

This will also work

>>> u=1./5
>>> print u
0.2

回答 8

如果要默认使用“ true”(浮点)除法,则有一个命令行标志:

python -Q new foo.py

有一些缺点(来自PEP):

有人认为,更改默认值的命令行选项是有害的。如果使用不当,肯定会很危险:例如,不可能将需要-Qnew的第三方库软件包与需要-Qold的第三方库软件包结合使用。

您可以通过查看python手册页了解有关更改/警告除法行为的其他标志值的更多信息。

有关除法更改的详细信息,请阅读:PEP 238-更改除法运算符

If you want to use “true” (floating point) division by default, there is a command line flag:

python -Q new foo.py

There are some drawbacks (from the PEP):

It has been argued that a command line option to change the default is evil. It can certainly be dangerous in the wrong hands: for example, it would be impossible to combine a 3rd party library package that requires -Qnew with another one that requires -Qold.

You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.

For full details on division changes read: PEP 238 — Changing the Division Operator


回答 9

from operator import truediv

c = truediv(a, b)
from operator import truediv

c = truediv(a, b)

回答 10

from operator import truediv

c = truediv(a, b)

其中a是除数,b是除数。当两个整数相除后的商是浮点数时,此函数非常方便。

from operator import truediv

c = truediv(a, b)

where a is dividend and b is the divisor. This function is handy when quotient after division of two integers is a float.


如何将字符串解析为float或int?

问题:如何将字符串解析为float或int?

在Python中,如何解析类似于"545.2222"其对应的float值的数字字符串545.2222?还是将字符串解析为"31"整数31

我只是想知道如何分析一个浮动 strfloat,和(单独)的INT strint

In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 545.2222? Or parse the string "31" to an integer, 31?

I just want to know how to parse a float str to a float, and (separately) an int str to an int.


回答 0

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

回答 1

def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)
def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

回答 2

检查字符串是否为浮点数的Python方法:

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

此功能的更长更准确的名称可能是: is_convertible_to_float(value)

什么是Python中的浮点数,哪些不是浮点数,可能会让您感到惊讶:

val                   is_float(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexadecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u'四'                 False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

您以为知道什么数字?你不像你想的那样好!并不奇怪。

不要在对生命至关重要的软件上使用此代码!

用这种方式捕获广泛的异常,杀死金丝雀和吞噬异常会产生很小的机会,即有效的float字符串将返回false。该float(...)行代码可以失败的任何什么都没有做的字符串的内容一千个理由。但是,如果您使用Python这样的鸭子式原型语言来编写至关重要的软件,那么您将遇到更大的问题。

Python method to check if a string is a float:

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

A longer and more accurate name for this function could be: is_convertible_to_float(value)

What is, and is not a float in Python may surprise you:

val                   is_float(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexadecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u'四'                 False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

Don’t use this code on life-critical software!

Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you’re writing life-critical software in a duck-typing prototype language like Python, then you’ve got much larger problems.


回答 3

这是另一个值得一提的方法ast.literal_eval

这可用于安全地评估包含来自不受信任来源的Python表达式的字符串,而无需自己解析值。

也就是说,一个安全的“评估”

>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31

This is another method which deserves to be mentioned here, ast.literal_eval:

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

That is, a safe ‘eval’

>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31

回答 4

float(x) if '.' in x else int(x)
float(x) if '.' in x else int(x)

回答 5

本地化和逗号

您应该考虑数字的字符串表示形式中可能出现逗号的情况,例如 float("545,545.2222")抛出异常的情况。而是使用in locale中的方法将字符串转换为数字并正确解释逗号。locale.atof一旦为所需的数字约定设置了语言环境,该方法便会一步转换为浮点数。

示例1-美国数字约定

在美国和英国,逗号可以用作千位分隔符。在具有美国语言环境的此示例中,逗号作为分隔符正确处理:

>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

示例2-欧洲数字约定

在世界上大多数国家/地区,逗号用于小数点而不是句点。在此使用法语语言环境的示例中,逗号被正确处理为小数点:

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

该方法locale.atoi也可用,但参数应为整数。

Localization and commas

You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222") which throws an exception. Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.

Example 1 — United States number conventions

In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:

>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

Example 2 — European number conventions

In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

The method locale.atoi is also available, but the argument should be an integer.


回答 6

如果您不喜欢第三方模块,则可以签出fastnumbers模块。它提供了一个名为fast_real的函数,该函数可以完全满足此问题的要求,并且比纯Python实现要快:

>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int

If you aren’t averse to third-party modules, you could check out the fastnumbers module. It provides a function called fast_real that does exactly what this question is asking for and does it faster than a pure-Python implementation:

>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int

回答 7

用户codelogicharley是正确的,但是请记住,如果您知道字符串是整数(例如545),则可以调用int(“ 545”)而不先进行浮点运算。

如果您的字符串在列表中,则也可以使用map函数。

>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>

只有它们都是相同的类型才是好的。

Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int(“545”) without first casting to float.

If your strings are in a list, you could use the map function as well.

>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>

It is only good if they’re all the same type.


回答 8

在Python中,如何将“ 545.2222”之类的数字字符串解析为其对应的浮点值542.2222?还是将字符串“ 31”解析为整数31? 我只想知道如何将float字符串解析为float,以及将int字符串分别解析为int。

您最好单独进行这些操作。如果您要混合使用它们,则可能会在以后遇到问题。简单的答案是:

"545.2222" 漂浮:

>>> float("545.2222")
545.2222

"31" 到一个整数:

>>> int("31")
31

其他与字符串和文字之间的转换,整数转换:

来自各种基准的转换,您应该事先知道基准(默认值为10)。请注意,您可以为它们加上Python期望的字面量(请参见下文)或删除前缀:

>>> int("0b11111", 2)
31
>>> int("11111", 2)
31
>>> int('0o37', 8)
31
>>> int('37', 8)
31
>>> int('0x1f', 16)
31
>>> int('1f', 16)
31

如果您不预先知道基础,但是您知道它们将具有正确的前缀,那么如果您通过0作为基础,Python可以为您推断出这个前缀:

>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31

其他基数的非十进制(即整数)文字

但是,如果您的动机是让自己的代码清楚地表示硬编码的特定值,则可能不需要从基数进行转换-您可以让Python使用正确的语法自动为您完成。

您可以使用apropos前缀自动转换为具有以下文字的整数。这些对Python 2和3有效:

二进制前缀 0b

>>> 0b11111
31

八进制,前缀 0o

>>> 0o37
31

十六进制,前缀 0x

>>> 0x1f
31

当描述二进制标志,代码中的文件许可权或颜色的十六进制值时,这很有用-例如,请注意不要使用引号:

>>> 0b10101 # binary flags
21
>>> 0o755 # read, write, execute perms for owner, read & ex for group & others
493
>>> 0xffffff # the color, white, max values for red, green, and blue
16777215

使模棱两可的Python 2八进制与Python 3兼容

如果您在Python 2中看到一个以0开头的整数,则这是(不建议使用的)八进制语法。

>>> 037
31

这很糟糕,因为看起来值应该是37。因此,在Python 3中,它现在引发了SyntaxError

>>> 037
  File "<stdin>", line 1
    037
      ^
SyntaxError: invalid token

使用0o前缀将Python 2八进制转换为在2和3中均可使用的八进制:

>>> 0o37
31

In Python, how can I parse a numeric string like “545.2222” to its corresponding float value, 542.2222? Or parse the string “31” to an integer, 31? I just want to know how to parse a float string to a float, and (separately) an int string to an int.

It’s good that you ask to do these separately. If you’re mixing them, you may be setting yourself up for problems later. The simple answer is:

"545.2222" to float:

>>> float("545.2222")
545.2222

"31" to an integer:

>>> int("31")
31

Other conversions, ints to and from strings and literals:

Conversions from various bases, and you should know the base in advance (10 is the default). Note you can prefix them with what Python expects for its literals (see below) or remove the prefix:

>>> int("0b11111", 2)
31
>>> int("11111", 2)
31
>>> int('0o37', 8)
31
>>> int('37', 8)
31
>>> int('0x1f', 16)
31
>>> int('1f', 16)
31

If you don’t know the base in advance, but you do know they will have the correct prefix, Python can infer this for you if you pass 0 as the base:

>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31

Non-Decimal (i.e. Integer) Literals from other Bases

If your motivation is to have your own code clearly represent hard-coded specific values, however, you may not need to convert from the bases – you can let Python do it for you automatically with the correct syntax.

You can use the apropos prefixes to get automatic conversion to integers with the following literals. These are valid for Python 2 and 3:

Binary, prefix 0b

>>> 0b11111
31

Octal, prefix 0o

>>> 0o37
31

Hexadecimal, prefix 0x

>>> 0x1f
31

This can be useful when describing binary flags, file permissions in code, or hex values for colors – for example, note no quotes:

>>> 0b10101 # binary flags
21
>>> 0o755 # read, write, execute perms for owner, read & ex for group & others
493
>>> 0xffffff # the color, white, max values for red, green, and blue
16777215

Making ambiguous Python 2 octals compatible with Python 3

If you see an integer that starts with a 0, in Python 2, this is (deprecated) octal syntax.

>>> 037
31

It is bad because it looks like the value should be 37. So in Python 3, it now raises a SyntaxError:

>>> 037
  File "<stdin>", line 1
    037
      ^
SyntaxError: invalid token

Convert your Python 2 octals to octals that work in both 2 and 3 with the 0o prefix:

>>> 0o37
31

回答 9

这个问题似乎有点老了。但是让我建议一个函数parseStr,它的功能类似,即返回整数或浮点数,并且如果无法将给定的ASCII字符串转换为其中的任何一个,则它将返回原样。当然,可以将代码调整为仅执行所需的操作:

   >>> import string
   >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
   ...                      int(x) or x.isalnum() and x or \
   ...                      len(set(string.punctuation).intersection(x)) == 1 and \
   ...                      x.count('.') == 1 and float(x) or x
   >>> parseStr('123')
   123
   >>> parseStr('123.3')
   123.3
   >>> parseStr('3HC1')
   '3HC1'
   >>> parseStr('12.e5')
   1200000.0
   >>> parseStr('12$5')
   '12$5'
   >>> parseStr('12.2.2')
   '12.2.2'

The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:

   >>> import string
   >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
   ...                      int(x) or x.isalnum() and x or \
   ...                      len(set(string.punctuation).intersection(x)) == 1 and \
   ...                      x.count('.') == 1 and float(x) or x
   >>> parseStr('123')
   123
   >>> parseStr('123.3')
   123.3
   >>> parseStr('3HC1')
   '3HC1'
   >>> parseStr('12.e5')
   1200000.0
   >>> parseStr('12$5')
   '12$5'
   >>> parseStr('12.2.2')
   '12.2.2'

回答 10

float("545.2222")int(float("545.2222"))

float("545.2222") and int(float("545.2222"))


回答 11

我为此使用此功能

import ast

def parse_str(s):
   try:
      return ast.literal_eval(str(s))
   except:
      return

它将字符串转换为其类型

value = parse_str('1')  # Returns Integer
value = parse_str('1.5')  # Returns Float

I use this function for that

import ast

def parse_str(s):
   try:
      return ast.literal_eval(str(s))
   except:
      return

It will convert the string to its type

value = parse_str('1')  # Returns Integer
value = parse_str('1.5')  # Returns Float

回答 12

YAML解析器可以帮助你找出你的数据类型的字符串是什么。使用yaml.load(),然后可以使用type(result)测试类型:

>>> import yaml

>>> a = "545.2222"
>>> result = yaml.load(a)
>>> result
545.22220000000004
>>> type(result)
<type 'float'>

>>> b = "31"
>>> result = yaml.load(b)
>>> result
31
>>> type(result)
<type 'int'>

>>> c = "HI"
>>> result = yaml.load(c)
>>> result
'HI'
>>> type(result)
<type 'str'>

The YAML parser can help you figure out what datatype your string is. Use yaml.load(), and then you can use type(result) to test for type:

>>> import yaml

>>> a = "545.2222"
>>> result = yaml.load(a)
>>> result
545.22220000000004
>>> type(result)
<type 'float'>

>>> b = "31"
>>> result = yaml.load(b)
>>> result
31
>>> type(result)
<type 'int'>

>>> c = "HI"
>>> result = yaml.load(c)
>>> result
'HI'
>>> type(result)
<type 'str'>

回答 13

def get_int_or_float(v):
    number_as_float = float(v)
    number_as_int = int(number_as_float)
    return number_as_int if number_as_float == number_as_int else number_as_float
def get_int_or_float(v):
    number_as_float = float(v)
    number_as_int = int(number_as_float)
    return number_as_int if number_as_float == number_as_int else number_as_float

回答 14

def num(s):
    """num(s)
    num(3),num(3.7)-->3
    num('3')-->3, num('3.7')-->3.7
    num('3,700')-->ValueError
    num('3a'),num('a3'),-->ValueError
    num('3e4') --> 30000.0
    """
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            raise ValueError('argument is not a string of number')
def num(s):
    """num(s)
    num(3),num(3.7)-->3
    num('3')-->3, num('3.7')-->3.7
    num('3,700')-->ValueError
    num('3a'),num('a3'),-->ValueError
    num('3e4') --> 30000.0
    """
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            raise ValueError('argument is not a string of number')

回答 15

您需要考虑到四舍五入才能正确执行此操作。

即int(5.1)=> 5 int(5.6)=> 5-错误,应该为6所以我们做int(5.6 + 0.5)=> 6

def convert(n):
    try:
        return int(n)
    except ValueError:
        return float(n + 0.5)

You need to take into account rounding to do this properly.

I.e. int(5.1) => 5 int(5.6) => 5 — wrong, should be 6 so we do int(5.6 + 0.5) => 6

def convert(n):
    try:
        return int(n)
    except ValueError:
        return float(n + 0.5)

回答 16

我很惊讶没有人提到正则表达式,因为有时必须在转换为数字之前准备好字符串并对其进行规范化

import re
def parseNumber(value, as_int=False):
    try:
        number = float(re.sub('[^.\-\d]', '', value))
        if as_int:
            return int(number + 0.5)
        else:
            return number
    except ValueError:
        return float('nan')  # or None if you wish

用法:

parseNumber('13,345')
> 13345.0

parseNumber('- 123 000')
> -123000.0

parseNumber('99999\n')
> 99999.0

顺便说一句,以验证您有一个数字:

import numbers
def is_number(value):
    return isinstance(value, numbers.Number)
    # will work with int, float, long, Decimal

I am surprised nobody mentioned regex because sometimes string must be prepared and normalized before casting to number

import re
def parseNumber(value, as_int=False):
    try:
        number = float(re.sub('[^.\-\d]', '', value))
        if as_int:
            return int(number + 0.5)
        else:
            return number
    except ValueError:
        return float('nan')  # or None if you wish

usage:

parseNumber('13,345')
> 13345.0

parseNumber('- 123 000')
> -123000.0

parseNumber('99999\n')
> 99999.0

and by the way, something to verify you have a number:

import numbers
def is_number(value):
    return isinstance(value, numbers.Number)
    # will work with int, float, long, Decimal

回答 17

要在python中进行类型转换,请使用该类型的构造函数,并将字符串(或您尝试投射的任何值)作为参数传递。

例如:

>>>float("23.333")
   23.333

在后台,python正在调用objects __float__方法,该方法应该返回参数的float表示形式。这是特别强大的功能,因为您可以使用__float__方法定义自己的类型(使用类),以便可以使用float(myobject)将其转换为float。

To typecast in python use the constructor funtions of the type, passing the string (or whatever value you are trying to cast) as a parameter.

For example:

>>>float("23.333")
   23.333

Behind the scenes, python is calling the objects __float__ method, which should return a float representation of the parameter. This is especially powerful, as you can define your own types (using classes) with a __float__ method so that it can be casted into a float using float(myobject).


回答 18

这是一个正确版本https://stackoverflow.com/a/33017514/5973334

这将尝试解析一个字符串并返回一个intfloat取决于该字符串表示什么。它可能会引发解析异常或具有某些意外行为

  def get_int_or_float(v):
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        return number_as_int if number_as_float == number_as_int else 
        number_as_float

This is a corrected version of https://stackoverflow.com/a/33017514/5973334

This will try to parse a string and return either int or float depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.

  def get_int_or_float(v):
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        return number_as_int if number_as_float == number_as_int else 
        number_as_float

回答 19

将您的字符串传递给此函数:

def string_to_number(str):
  if("." in str):
    try:
      res = float(str)
    except:
      res = str  
  elif(str.isdigit()):
    res = int(str)
  else:
    res = str
  return(res)

根据所传递的内容,它将返回int,float或string。

一个int字符串

print(type(string_to_number("124")))
<class 'int'>

浮点数的字符串

print(type(string_to_number("12.4")))
<class 'float'>

字符串即字符串

print(type(string_to_number("hello")))
<class 'str'>

看起来像个浮点数的字符串

print(type(string_to_number("hel.lo")))
<class 'str'>

Pass your string to this function:

def string_to_number(str):
  if("." in str):
    try:
      res = float(str)
    except:
      res = str  
  elif(str.isdigit()):
    res = int(str)
  else:
    res = str
  return(res)

It will return int, float or string depending on what was passed.

string that is an int

print(type(string_to_number("124")))
<class 'int'>

string that is a float

print(type(string_to_number("12.4")))
<class 'float'>

string that is a string

print(type(string_to_number("hello")))
<class 'str'>

string that looks like a float

print(type(string_to_number("hel.lo")))
<class 'str'>

回答 20

采用:

def num(s):
    try:
        for each in s:
            yield int(each)
    except ValueError:
        yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()

这是我想出的最Python化的方式。

Use:

def num(s):
    try:
        for each in s:
            yield int(each)
    except ValueError:
        yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()

This is the most Pythonic way I could come up with.


回答 21

处理十六进制,八进制,二进制,十进制和浮点数

该解决方案将处理数字的所有字符串约定(我所知道的全部)。

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

该测试用例输出说明了我在说什么。

======================== CAPTURED OUTPUT =========================
to_number(3735928559)   = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0")        =          0 ==          0
to_number(100)          =        100 ==        100
to_number("42")         =         42 ==         42
to_number(8)            =          8 ==          8
to_number("0o20")       =         16 ==         16
to_number("020")        =         16 ==         16
to_number(3.14)         =       3.14 ==       3.14
to_number("2.72")       =       2.72 ==       2.72
to_number("1e3")        =     1000.0 ==       1000
to_number(0.001)        =      0.001 ==      0.001
to_number("0xA")        =         10 ==         10
to_number("012")        =         10 ==         10
to_number("0o12")       =         10 ==         10
to_number("0b01010")    =         10 ==         10
to_number("10")         =         10 ==         10
to_number("10.0")       =       10.0 ==         10
to_number("1e1")        =       10.0 ==         10

这是测试:

class test_to_number(unittest.TestCase):

    def test_hex(self):
        # All of the following should be converted to an integer
        #
        values = [

                 #          HEX
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0xDEADBEEF  , 3735928559), # Hex
                ("0xFEEDFACE", 4277009102), # Hex
                ("0x0"       ,          0), # Hex

                 #        Decimals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (100         ,        100), # Decimal
                ("42"        ,         42), # Decimal
            ]



        values += [
                 #        Octals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0o10        ,          8), # Octal
                ("0o20"      ,         16), # Octal
                ("020"       ,         16), # Octal
            ]


        values += [
                 #        Floats
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (3.14        ,       3.14), # Float
                ("2.72"      ,       2.72), # Float
                ("1e3"       ,       1000), # Float
                (1e-3        ,      0.001), # Float
            ]

        values += [
                 #        All ints
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                ("0xA"       ,         10), 
                ("012"       ,         10), 
                ("0o12"      ,         10), 
                ("0b01010"   ,         10), 
                ("10"        ,         10), 
                ("10.0"      ,         10), 
                ("1e1"       ,         10), 
            ]

        for _input, expected in values:
            value = to_number(_input)

            if isinstance(_input, str):
                cmd = 'to_number("{}")'.format(_input)
            else:
                cmd = 'to_number({})'.format(_input)

            print("{:23} = {:10} == {:10}".format(cmd, value, expected))
            self.assertEqual(value, expected)

Handles hex, octal, binary, decimal, and float

This solution will handle all of the string conventions for numbers (all that I know about).

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

This test case output illustrates what I’m talking about.

======================== CAPTURED OUTPUT =========================
to_number(3735928559)   = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0")        =          0 ==          0
to_number(100)          =        100 ==        100
to_number("42")         =         42 ==         42
to_number(8)            =          8 ==          8
to_number("0o20")       =         16 ==         16
to_number("020")        =         16 ==         16
to_number(3.14)         =       3.14 ==       3.14
to_number("2.72")       =       2.72 ==       2.72
to_number("1e3")        =     1000.0 ==       1000
to_number(0.001)        =      0.001 ==      0.001
to_number("0xA")        =         10 ==         10
to_number("012")        =         10 ==         10
to_number("0o12")       =         10 ==         10
to_number("0b01010")    =         10 ==         10
to_number("10")         =         10 ==         10
to_number("10.0")       =       10.0 ==         10
to_number("1e1")        =       10.0 ==         10

Here is the test:

class test_to_number(unittest.TestCase):

    def test_hex(self):
        # All of the following should be converted to an integer
        #
        values = [

                 #          HEX
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0xDEADBEEF  , 3735928559), # Hex
                ("0xFEEDFACE", 4277009102), # Hex
                ("0x0"       ,          0), # Hex

                 #        Decimals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (100         ,        100), # Decimal
                ("42"        ,         42), # Decimal
            ]



        values += [
                 #        Octals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0o10        ,          8), # Octal
                ("0o20"      ,         16), # Octal
                ("020"       ,         16), # Octal
            ]


        values += [
                 #        Floats
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (3.14        ,       3.14), # Float
                ("2.72"      ,       2.72), # Float
                ("1e3"       ,       1000), # Float
                (1e-3        ,      0.001), # Float
            ]

        values += [
                 #        All ints
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                ("0xA"       ,         10), 
                ("012"       ,         10), 
                ("0o12"      ,         10), 
                ("0b01010"   ,         10), 
                ("10"        ,         10), 
                ("10.0"      ,         10), 
                ("1e1"       ,         10), 
            ]

        for _input, expected in values:
            value = to_number(_input)

            if isinstance(_input, str):
                cmd = 'to_number("{}")'.format(_input)
            else:
                cmd = 'to_number({})'.format(_input)

            print("{:23} = {:10} == {:10}".format(cmd, value, expected))
            self.assertEqual(value, expected)

回答 22

采用:

>>> str_float = "545.2222"
>>> float(str_float)
545.2222
>>> type(_) # Check its type
<type 'float'>

>>> str_int = "31"
>>> int(str_int)
31
>>> type(_) # Check its type
<type 'int'>

Use:

>>> str_float = "545.2222"
>>> float(str_float)
545.2222
>>> type(_) # Check its type
<type 'float'>

>>> str_int = "31"
>>> int(str_int)
31
>>> type(_) # Check its type
<type 'int'>

回答 23

这是将转换任何一个函数object(不只是str)到intfloat方法,依据实际的字符串提供模样 intfloat。此外,如果它是同时具有__float__int__方法的对象,则默认使用__float__

def conv_to_num(x, num_type='asis'):
    '''Converts an object to a number if possible.
    num_type: int, float, 'asis'
    Defaults to floating point in case of ambiguity.
    '''
    import numbers

    is_num, is_str, is_other = [False]*3

    if isinstance(x, numbers.Number):
        is_num = True
    elif isinstance(x, str):
        is_str = True

    is_other = not any([is_num, is_str])

    if is_num:
        res = x
    elif is_str:
        is_float, is_int, is_char = [False]*3
        try:
            res = float(x)
            if '.' in x:
                is_float = True
            else:
                is_int = True
        except ValueError:
            res = x
            is_char = True

    else:
        if num_type == 'asis':
            funcs = [int, float]
        else:
            funcs = [num_type]

        for func in funcs:
            try:
                res = func(x)
                break
            except TypeError:
                continue
        else:
            res = x

This is a function which will convert any object (not just str) to int or float, based on if the actual string supplied looks like int or float. Further if it’s an object which has both __float and __int__ methods, it defaults to using __float__

def conv_to_num(x, num_type='asis'):
    '''Converts an object to a number if possible.
    num_type: int, float, 'asis'
    Defaults to floating point in case of ambiguity.
    '''
    import numbers

    is_num, is_str, is_other = [False]*3

    if isinstance(x, numbers.Number):
        is_num = True
    elif isinstance(x, str):
        is_str = True

    is_other = not any([is_num, is_str])

    if is_num:
        res = x
    elif is_str:
        is_float, is_int, is_char = [False]*3
        try:
            res = float(x)
            if '.' in x:
                is_float = True
            else:
                is_int = True
        except ValueError:
            res = x
            is_char = True

    else:
        if num_type == 'asis':
            funcs = [int, float]
        else:
            funcs = [num_type]

        for func in funcs:
            try:
                res = func(x)
                break
            except TypeError:
                continue
        else:
            res = x

回答 24

通过使用int和float方法,我们可以将字符串转换为整数和浮点数。

s="45.8"
print(float(s))

y='67'
print(int(y))

By using int and float methods we can convert a string to integer and floats.

s="45.8"
print(float(s))

y='67'
print(int(y))

回答 25

eval()是这个问题的很好解决方案。它不需要检查数字是int还是float,它只给出相应的等价物。如果需要其他方法,请尝试

if '.' in string:
    print(float(string))
else:
    print(int(string))

try-except也可以用作替代方法。尝试在try块中将字符串转换为int。如果该字符串是一个浮点值,它将抛出一个错误,该错误将在except块中捕获,像这样

try:
    print(int(string))
except:
    print(float(string))

eval() is a very good solution to this question. It doesn’t need to check if the number is int or float, it just gives the corresponding equivalent. If other methods are required, try

if '.' in string:
    print(float(string))
else:
    print(int(string))

try-except can also be used as an alternative. Try converting string to int inside the try block. If the string would be a float value, it will throw an error which will be catched in the except block, like this

try:
    print(int(string))
except:
    print(float(string))

回答 26

这是您问题的另一种解释(提示:含糊)。您可能正在寻找这样的东西:

def parseIntOrFloat( aString ):
    return eval( aString )

它是这样的…

>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

从理论上讲,存在注入漏洞。字符串可以是例如"import os; os.abort()"。但是,由于没有关于字符串来自何处的任何背景,因此可能是理论上的推测。由于问题很模糊,因此尚不清楚此漏洞是否确实存在。

Here’s another interpretation of your question (hint: it’s vague). It’s possible you’re looking for something like this:

def parseIntOrFloat( aString ):
    return eval( aString )

It works like this…

>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

Theoretically, there’s an injection vulnerability. The string could, for example be "import os; os.abort()". Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it’s not at all clear if this vulnerability actually exists or not.


将整数转换为字符串?

问题:将整数转换为字符串?

我想在Python中将整数转换为字符串。我是徒劳地打字:

d = 15
d.str()

当我尝试将其转换为字符串时,它显示错误,例如int没有任何名为的属性str

I want to convert an integer to a string in Python. I am typecasting it in vain:

d = 15
d.str()

When I try to convert it to string, it’s showing an error like int doesn’t have any attribute called str.


回答 0

>>> str(10)
'10'
>>> int('10')
10

链接到文档:

转换为字符串是通过内置str()函数完成的,该函数基本上调用__str__()其参数的方法。

>>> str(10)
'10'
>>> int('10')
10

Links to the documentation:

Conversion to a string is done with the builtin str() function, which basically calls the __str__() method of its parameter.


回答 1

尝试这个:

str(i)

Try this:

str(i)

回答 2

Python中没有类型转换,也没有类型强制。您必须以显式方式转换变量。

要使用字符串转换对象,请使用str()函数。它适用于具有称为__str__()define 的方法的任何对象。事实上

str(a)

相当于

a.__str__()

如果要将某些内容转换为int,float等,则相同。

There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.

To convert an object in string you use the str() function. It works with any object that has a method called __str__() defined. In fact

str(a)

is equivalent to

a.__str__()

The same if you want to convert something to int, float, etc.


回答 3

要管理非整数输入:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0

To manage non-integer inputs:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0

回答 4

>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5
>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5

回答 5

在Python => 3.6中,您可以使用f格式:

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>

In Python => 3.6 you can use f formatting:

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>

回答 6

对于Python 3.6,您可以使用f-strings新功能将其转换为字符串,并且与str()函数相比,它更快,它的用法如下:

age = 45
strAge = f'{age}'

因此,Python提供了str()函数。

digit = 10
print(type(digit)) # will show <class 'int'>
convertedDigit= str(digit)
print(type(convertedDigit)) # will show <class 'str'>

有关更多详细的答案,请查看本文:将Python Int转换为String并将Python String转换为Int

For Python 3.6 you can use the f-strings new feature to convert to string and it’s faster compared to str() function, it is used like that:

age = 45
strAge = f'{age}'

Python provides the str() function for that reason.

digit = 10
print(type(digit)) # will show <class 'int'>
convertedDigit= str(digit)
print(type(convertedDigit)) # will show <class 'str'>

For more detailed answer you can check this article: Converting Python Int to String and Python String to Int


回答 7

我认为最体面的方式是“。

i = 32   -->    `i` == '32'

The most decent way in my opinion is “.

i = 32   -->    `i` == '32'

回答 8

可以使用%s.format

>>> "%s" % 10
'10'
>>>

(要么)

>>> '{}'.format(10)
'10'
>>>

Can use %s or .format

>>> "%s" % 10
'10'
>>>

(OR)

>>> '{}'.format(10)
'10'
>>>

回答 9

对于想要将int转换为特定数字的字符串的人,建议使用以下方法。

month = "{0:04d}".format(localtime[1])

有关更多详细信息,您可以参考堆栈溢出问题显示数字前导零

For someone who wants to convert int to string in specific digits, the below method is recommended.

month = "{0:04d}".format(localtime[1])

For more details, you can refer to Stack Overflow question Display number with leading zeros.


回答 10

通过在Python 3.6中引入f字符串,这也将起作用:

f'{10}' == '10'

实际上str(),它比调用速度更快,但会降低可读性。

实际上,它比%x字符串格式和.format()!快。

With the introduction of f-strings in Python 3.6, this will also work:

f'{10}' == '10'

It is actually faster than calling str(), at the cost of readability.

In fact, it’s faster than %x string formatting and .format()!