问题:如何在Python中将字符转换为整数,反之亦然?
我想要获得一个角色的ASCII
价值。
例如,对于角色a
,我要获取97
,反之亦然。
回答 0
回答 1
>>> ord('a')
97
>>> chr(97)
'a'
回答 2
ord和chr
如何使用Python文字将整数表示为二进制数?
我很容易找到十六进制的答案:
>>> 0x12AF
4783
>>> 0x100
256
和八进制:
>>> 01267
695
>>> 0100
64
您如何使用文字在Python中表示二进制?
答案摘要
int('01010101111',2)
但不能使用文字来表示二进制。0b1100111
或0B1100111
。0o27
或0O27
(第二个字符是字母O)表示一个八进制。027
的八进制语法。供参考- 未来的 Python可能性:
从Python 2.6开始,您可以使用前缀0b或0B表示二进制文字:
>>> 0b101111
47
您还可以使用新的bin函数来获取数字的二进制表示形式:
>>> bin(173)
'0b10101101'
文档的开发版本:Python 2.6的新增功能
>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255
另一种方式。
您如何用Python表达二进制文字?
它们不是“二进制”文字,而是“整数文字”。您可以用二进制格式表示整数文字,0
后跟a B
或b
后跟一系列零和一,例如:
>>> 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
您可以选择使用0b
或0B
前缀:
>>> int('0b0010101010', 2)
170
如果将其0
作为基数传递,则如果字符串未指定前缀,则它将假定基数为10:
>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21
您可以将整数传递给bin以查看二进制文字的字符串表示形式:
>>> bin(21)
'0b10101'
你可以结合bin
并int
去来回:
>>> bin(int('010101', 2))
'0b10101'
如果希望最小宽度和前面的零,也可以使用格式规范:
>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'
开头的0表示底数是8(而不是10),这很容易看到:
>>> int('010101', 0)
4161
如果您不以0开头,则python假定数字以10为底。
>>> int('10101', 0)
10101
据我所知,直到2.5,Python仅支持十六进制和八进制文字。我确实找到了一些有关在将来的版本中添加二进制文件的讨论,但没有明确的定义。
我很确定这是由于Python 3.0的变化之一,也许bin()与hex()和oct()一起使用。
编辑:lbrandy的答案在所有情况下都是正确的。
这个问题使我丧命。如何在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!
请指教。
该小区(上限)功能:
import math
print(math.ceil(4.2))
我知道这个答案是一个很久以前的问题,但是如果您不想导入数学并且只想四舍五入,那么这对我有用。
>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5
如果有余数,则第一部分将变为4,第二部分将得出“ True”,另外,True = 1; False =0。因此,如果没有余数,则它将保持相同的整数,但是如果有余数,则将其加1。
请记住有趣的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
如果使用整数,则四舍五入的一种方法是利用四舍五入的事实//
:只需对负数进行除法,然后取反即可。无需导入,浮点或有条件的。
rounded_up = -(-numerator // denominator)
例如:
>>> print(-(-101 // 5))
21
您可能还喜欢numpy:
>>> import numpy as np
>>> np.ceil(2.3)
3.0
我并不是说它比数学更好,但是如果您已经将numpy用于其他目的,则可以使代码保持一致。
无论如何,我遇到的只是一个细节。我经常使用numpy,但感到惊讶的是它没有被提及,但是当然可以接受。
使用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)
语法可能不像pythonic那样,但是它是一个功能强大的库。
https://docs.python.org/2/library/decimal.html
from decimal import *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))
我很惊讶没有人建议
(numerator + denominator - 1) // denominator
用于四舍五入的整数除法。曾经是C / C ++ / CUDA的常用方法(参见divup
)
请确保四舍五入的值应为浮点型
a = 8
b = 21
print math.ceil(a / b)
>>> 0
但
print math.ceil(float(a) / b)
>>> 1.0
尝试这个:
a = 211.0
print(int(a) + ((int(a) - a) != 0))
>>> def roundup(number):
... return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20
此功能不需要任何模块。
上面的答案是正确的,但是,math
对于这个功能而言,导入模块通常对我来说有点过头了。幸运的是,还有另一种方法可以做到:
g = 7/5
g = int(g) + (not g.is_integer())
True
并且在python中涉及数字的语句中False
被解释为1
和0
。g.is_interger()
基本上翻译为g.has_no_decimal()
或g == int(g)
。因此,最后的英文陈述为round g down and add one if g has decimal
。
无需导入数学//使用基本环境:
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)
对于那些想要四舍五入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
如果有人希望将其舍入到小数点后一位:
import math
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier
令我惊讶的是我还没有看到这个答案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
,但这不太可能。
要做到这一点而无需任何导入:
>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3
我知道这已经有一段时间了,但是我找到了一个非常有趣的答案,所以可以这样:
-round(-x-0.5)
这可以修复边缘情况,并且适用于正数和负数,并且不需要任何函数导入
干杯
当您在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
祝好运!!
如果您不想导入任何内容,则可以始终将自己的简单函数编写为:
def RoundUP(num):
if num== int(num):
return num
return int(num + 1)
您可以使用楼层划分并将其添加1。2.3 // 2 + 1
我认为您会混淆int()
和之间的工作机制round()
。
int()
如果给出浮点数,则总是截断十进制数;相反round()
,如果2.5
where 2
和3
are都在等距离内2.5
,则Python返回距离0点更远的那个。
round(2.5) = 3
int(2.5) = 2
我的份额
我已经测试 print(-(-101 // 5)) = 21
了上面给出的示例。
现在进行四舍五入:
101 * 19% = 19.19
我不能使用,**
所以我将乘法扩展到除法:
(-(-101 //(1/0.19))) = 20
我基本上是Python的初学者,但是如果您只是想舍入而不是舍弃,那为什么不做:
round(integer) + 1
有没有办法在不使用try / except机制的情况下判断字符串是否表示一个整数(例如'3'
,'-17'
但不是'3.14'
或'asfasfas'
)?
is_int('3.14') = False
is_int('-7') = True
如果您真的很讨厌在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。
使用正整数可以使用.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()
您知道,无论出于何种原因,我都发现(并且已经对此进行了反复测试)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,因此。我猜,选择你的毒药。
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
使用正则表达式:
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()
。
适当的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
>>> "+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()
Greg Hewgill的方法缺少一些组件:前导“ ^”只匹配字符串的开头,然后预先编译re。但是这种方法将使您避免尝试:专家:
import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
return INT_RE.match(str(s)) is not None
我很想知道为什么您要尝试避免尝试:除了?
我必须一直这样做,而且我对使用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)])
至少有两种(边缘?)情况会崩溃:
type(1E2)
给出了<class 'float'>
而type(10^2)
给出了<class 'int'>
。因此,它不适用于所有可能的输入,但是如果您可以排除科学计数法,指数计数法和空字符串,则可以单行检查,False
如果x不是整数,True
并且x是整数,则返回单行检查。
我不知道它是否是pythonic,但这只是一行,而且相对清楚代码的作用。
我认为
s.startswith('-') and s[1:].isdigit()
最好重写为:
s.replace('-', '').isdigit()
因为s [1:]也创建了一个新字符串
但是更好的解决方案是
s.lstrip('+-').isdigit()
我真的很喜欢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年)执行的同一测试中击败了字符串比较。也许正则表达式库得到了改进?
在我看来,这可能是最直接,最Python的方法。我没有看到这种解决方案,它与regex基本相同,但是没有regex。
def is_int(test):
import string
return not (set(test) - set(string.digits))
这是一个不会引起错误的解析函数。它处理明显的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
我建议以下内容:
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
¯\ _(ツ)_ /¯
我有一种根本不使用int的可能性,并且除非字符串不代表数字,否则不应引发异常
float(number)==float(number)//1
它应该适用于float接受的任何类型的字符串(正,负,工程符号)。
我猜这个问题与速度有关,因为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)
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解决方案要快得多。
如果您只想接受低位数字,请执行以下测试:
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
嗯。尝试这个:
def int_check(a):
if int(a) == a:
return True
else:
return False
如果您不输入不是数字的字符串,则此方法有效。
而且(我忘了放数字检查部分。),还有一个函数检查字符串是否是数字。它是str.isdigit()。这是一个例子:
a = 2
a.isdigit()
如果调用a.isdigit(),它将返回True。
我有一个来自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
但是还没有得到令人满意的结果。
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]
您可以通过列表理解来做到这一点:
T2 = [[int(column) for column in row] for row in T1]
内部列表理解([int(column) for column in row]
)建立一个list
的int
期从序列int
-able物体,如小数字符串中row
。外部列表推导([... for row in T1])
)生成一个内部列表推导的结果的列表,该结果适用于中的每个项目T1
。
如果任何行包含无法通过转换的对象,则代码段将失败int
。如果要处理包含非十进制字符串的行,则需要一个更智能的函数。
如果您知道行的结构,则可以使用对行函数的调用来替换内部列表理解。例如。
T2 = [parse_a_row_of_T1(row) for row in T1]
我宁愿只使用理解列表:
[[int(y) for y in x] for x in T1]
代替put int( )
,put float( )
可以让您将小数与整数一起使用。
到目前为止,我都同意所有人的回答,但是问题是,如果您没有所有整数,它们将崩溃。
如果要排除非整数,则
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())
这仅产生实际数字。我不使用直接列表推导的原因是因为列表推导会泄漏其内部变量。
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
尝试这个。
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中没有数字。
使用列表推导:
t2 = [map(int, list(l)) for l in t1]
在Python 3.5.1中,这些工作如下:
c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))
和
Enter number: 4.7
4
5
乔治。
查看此功能
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:'
适用于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)
如果只是元组的元组,类似 rows=[map(int, row) for row in rows]
就可以解决。(在其中有一个列表推导和对map(f,lst)的调用,该调用等于[f in a lst]中的f(a)。)
如果由于某种原因在数据库中有类似的东西,Eval 不是您想要做的__import__("os").unlink("importantsystemfile")
。始终验证您的输入(如果没有其他问题,如果输入错误,则会引发int()异常)。
您可以执行以下操作:
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)
我想分享一个似乎此处未提及的可用选项:
rumpy.random.permutation(x)
将生成数组x的随机排列。不完全是您的要求,但这是解决类似问题的潜在方法。
鉴于:
a = 1
b = 10
c = 100
如何为少于两位的所有数字显示前导零?
这是我期望的输出:
01
10
100
在Python 2(和Python 3)中,您可以执行以下操作:
print "%02d" % (1,)
基本上%就像printf
或sprintf
(请参阅docs)。
对于Python 3. +,也可以通过以下方式实现相同的行为format
:
print("{:02d}".format(1))
对于Python 3.6+,可以使用f-strings实现相同的行为:
print(f"{1:02d}")
您可以使用str.zfill
:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
印刷品:
01
10
100
在Python 2.6+和3.0+中,您将使用format()
字符串方法:
for i in (1, 10, 100):
print('{num:02d}'.format(num=i))
或使用内置的(对于单个数字):
print(format(i, '02d'))
有关新的格式化功能,请参阅PEP-3101文档。
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))
印刷品:
01
10
100
或这个:
print '{0:02d}'.format(1)
在Python> = 3.6中,您可以使用以下命令引入的新f字符串来简洁地执行此操作:
f'{val:02}'
它打印用名称的变量val
具有fill
的值0
和width
的2
。
对于您的特定示例,您可以在循环中很好地做到这一点:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
打印:
01
10
100
有关f弦的更多信息,请查看引入它们的PEP 498。
使用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
或其他解决方案。
"{:0>2}".format(number)
使用格式字符串-http://docs.python.org/lib/typesseq-strings.html
例如:
python -c 'print "%(num)02d" % {"num":5}'
这是我的方法:
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 >>>
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted
您可以使用f字符串执行此操作。
import numpy as np
print(f'{np.random.choice([1, 124, 13566]):0>8}')
这将打印恒定长度的8,并用领先的填充0
。
00000001
00000124
00013566
采用:
'00'[len(str(i)):] + str(i)
或与math
模块:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
df['Col1']=df['Col1'].apply(lambda x: '{0:0>5}'.format(x))
5是总位数。
我使用了以下链接:http : //www.datasciencemadesimple.com/add-leading-preceding-zeros-python/
如果处理的是一位或两位数字:
'0'+str(number)[-2:]
要么 '0{0}'.format(number)[-2:]
我正在寻找python中整数的最小值和最大值。例如,在Java中,我们有Integer.MIN_VALUE
和Integer.MAX_VALUE
。python中是否有类似的东西?
在Python 3中,此问题不适用。普通int
类型是无界的。
但是,您实际上可能正在寻找有关当前解释器的字长的信息,在大多数情况下,该信息将与机器的字长相同。该信息仍在Python 3中以形式提供sys.maxsize
,这是一个有符号的单词可以表示的最大值。等效地,它是最大可能列表或内存序列的大小。
通常,无符号字可表示的最大值为,字中sys.maxsize * 2 + 1
的位数为math.log2(sys.maxsize * 2 + 2)
。有关更多信息,请参见此答案。
在Python 2中,纯int
值的最大值可作为sys.maxint
:
>>> sys.maxint
9223372036854775807
你可以计算与最小值-sys.maxint - 1
如图所示这里。
一旦超过此值,Python就会从纯整数无缝转换为长整数。因此,大多数时候,您不需要了解它。
如果您只需要一个大于所有其他数字的数字,则可以使用
float('inf')
以类似的方式,比所有其他方法小:
float('-inf')
这适用于python 2和3。
该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。
在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
对于Python 3,它是
import sys
max = sys.maxsize
min = -sys.maxsize - 1
如果您想要数组或列表索引的最大值(相当于size_t
C / C ++),则可以使用numpy:
np.iinfo(np.intp).max
这是相同的,sys.maxsize
但是优点是您不需要为此仅导入sys。
如果要在计算机上将max用于本机int:
np.iinfo(np.intc).max
您可以在doc中查看其他可用类型。
对于float,您也可以使用sys.float_info.max
。
我严重依赖这样的命令。
python -c 'import sys; print(sys.maxsize)'
返回的最大整数:9223372036854775807
有关“ sys”的更多参考,请访问
我有两个整数值a
和b
,但是我需要它们在浮点数中的比率。我知道a < b
并且想要计算a / b
,所以如果我使用整数除法,我将总是得到0,余数为a
。
c
在下文中,如何在Python中强制成为浮点数?
c = a / b
在Python 2中,两个整数的除法产生一个整数。在Python 3中,它产生一个浮点数。我们可以通过从中导入来获得新的行为__future__
。
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
您可以通过执行此操作来浮动c = a / float(b)
。如果分子或分母是浮点数,则结果也将是。
一个警告:如评论员所指出的,如果b
它不是整数或浮点数(或表示一个的字符串),则此方法将无效。如果您正在处理其他类型(例如复数),则需要检查这些类型或使用其他方法。
如何在Python中强制除法为浮点数?
我有两个整数值a和b,但是我需要它们在浮点数中的比率。我知道a <b并且我想计算a / b,所以如果我使用整数除法,我总是得到0并得到a的余数。
下面如何在Python中强制c为浮点数?
c = a / b
这里真正要问的是:
“我如何强制进行真正的除法以a / b
返回分数?”
在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 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向前兼容。
如果您不想将其应用于整个模块,则只能使用一些解决方法。最受欢迎的是将其中一个操作数强制为浮点数。一种可靠的解决方案是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
常见的是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
c = a / (b * 1.0)
在Python 3.x中,单斜杠(/
)始终表示真实(非截断)除法。(//
运算符用于截断除法。)在Python 2.x(2.2及更高版本)中,您可以通过将
from __future__ import division
在模块顶部。
仅以浮点格式进行除法的任何参数也会产生浮点输出。
例:
>>> 4.0/3
1.3333333333333333
要么,
>>> 4 / 3.0
1.3333333333333333
要么,
>>> 4 / float(3)
1.3333333333333333
要么,
>>> float(4) / 3
1.3333333333333333
加一个点(.
)表示浮点数
>>> 4/3.
1.3333333333333333
这也可以
>>> u=1./5
>>> print u
0.2
如果要默认使用“ true”(浮点)除法,则有一个命令行标志:
python -Q new foo.py
有一些缺点(来自PEP):
有人认为,更改默认值的命令行选项是有害的。如果使用不当,肯定会很危险:例如,不可能将需要-Qnew的第三方库软件包与需要-Qold的第三方库软件包结合使用。
您可以通过查看python手册页了解有关更改/警告除法行为的其他标志值的更多信息。
有关除法更改的详细信息,请阅读:PEP 238-更改除法运算符
from operator import truediv
c = truediv(a, b)
from operator import truediv
c = truediv(a, b)
其中a是除数,b是除数。当两个整数相除后的商是浮点数时,此函数非常方便。
在Python中,如何解析类似于"545.2222"
其对应的float值的数字字符串545.2222
?还是将字符串解析为"31"
整数31
?
我只是想知道如何分析一个浮动 str
的float
,和(单独)的INT str
到int
。
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
def num(s):
try:
return int(s)
except ValueError:
return float(s)
def is_float(value):
try:
float(value)
return True
except:
return False
此功能的更长更准确的名称可能是: is_convertible_to_float(value)
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这样的鸭子式原型语言来编写至关重要的软件,那么您将遇到更大的问题。
这是另一个值得一提的方法ast.literal_eval:
这可用于安全地评估包含来自不受信任来源的Python表达式的字符串,而无需自己解析值。
也就是说,一个安全的“评估”
>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31
float(x) if '.' in x else int(x)
您应该考虑数字的字符串表示形式中可能出现逗号的情况,例如 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
也可用,但参数应为整数。
如果您不喜欢第三方模块,则可以签出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
用户codelogic和harley是正确的,但是请记住,如果您知道字符串是整数(例如545),则可以调用int(“ 545”)而不先进行浮点运算。
如果您的字符串在列表中,则也可以使用map函数。
>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>
只有它们都是相同的类型才是好的。
在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中看到一个以0开头的整数,则这是(不建议使用的)八进制语法。
>>> 037
31
这很糟糕,因为看起来值应该是37
。因此,在Python 3中,它现在引发了SyntaxError
:
>>> 037
File "<stdin>", line 1
037
^
SyntaxError: invalid token
使用0o
前缀将Python 2八进制转换为在2和3中均可使用的八进制:
>>> 0o37
31
这个问题似乎有点老了。但是让我建议一个函数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'
float("545.2222")
和 int(float("545.2222"))
我为此使用此功能
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
该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'>
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 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')
您需要考虑到四舍五入才能正确执行此操作。
即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)
我很惊讶没有人提到正则表达式,因为有时必须在转换为数字之前准备好字符串并对其进行规范化
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
要在python中进行类型转换,请使用该类型的构造函数,并将字符串(或您尝试投射的任何值)作为参数传递。
例如:
>>>float("23.333")
23.333
在后台,python正在调用objects __float__
方法,该方法应该返回参数的float表示形式。这是特别强大的功能,因为您可以使用__float__
方法定义自己的类型(使用类),以便可以使用float(myobject)将其转换为float。
这是一个正确版本的 https://stackoverflow.com/a/33017514/5973334
这将尝试解析一个字符串并返回一个int
或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
将您的字符串传递给此函数:
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'>
采用:
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化的方式。
处理十六进制,八进制,二进制,十进制和浮点数
该解决方案将处理数字的所有字符串约定(我所知道的全部)。
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)
采用:
>>> 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'>
这是将转换任何一个函数object
(不只是str
)到int
或float
方法,依据实际的字符串提供模样 int
或float
。此外,如果它是同时具有__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
通过使用int和float方法,我们可以将字符串转换为整数和浮点数。
s="45.8"
print(float(s))
y='67'
print(int(y))
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))
这是您问题的另一种解释(提示:含糊)。您可能正在寻找这样的东西:
def parseIntOrFloat( aString ):
return eval( aString )
它是这样的…
>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545
从理论上讲,存在注入漏洞。字符串可以是例如"import os; os.abort()"
。但是,由于没有关于字符串来自何处的任何背景,因此可能是理论上的推测。由于问题很模糊,因此尚不清楚此漏洞是否确实存在。
我想在Python中将整数转换为字符串。我是徒劳地打字:
d = 15
d.str()
当我尝试将其转换为字符串时,它显示错误,例如int
没有任何名为的属性str
。
尝试这个:
str(i)
Python中没有类型转换,也没有类型强制。您必须以显式方式转换变量。
要使用字符串转换对象,请使用str()
函数。它适用于具有称为__str__()
define 的方法的任何对象。事实上
str(a)
相当于
a.__str__()
如果要将某些内容转换为int,float等,则相同。
要管理非整数输入:
number = raw_input()
try:
value = int(number)
except ValueError:
value = 0
>>> 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
在Python => 3.6中,您可以使用f
格式:
>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
对于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
我认为最体面的方式是“。
i = 32 --> `i` == '32'
可以使用%s
或.format
>>> "%s" % 10
'10'
>>>
(要么)
>>> '{}'.format(10)
'10'
>>>
通过在Python 3.6中引入f字符串,这也将起作用:
f'{10}' == '10'
实际上str()
,它比调用速度更快,但会降低可读性。
实际上,它比%x
字符串格式和.format()
!快。