检查字符串是否可以在Python中表示为数字的最佳方法是什么?
我目前拥有的功能是:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Run Code Online (Sandbox Code Playgroud)
这不仅是丑陋而且缓慢,似乎很笨重.但是我没有找到更好的方法,因为调用float
main函数更糟糕.
我有一些Python代码通过一个字符串列表运行,如果可能的话将它们转换为整数或浮点数.对整数执行此操作非常简单
if element.isdigit():
newelement = int(element)
Run Code Online (Sandbox Code Playgroud)
浮点数更难.现在我正在使用partition('.')
拆分字符串并检查以确保一侧或两侧是数字.
partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit())
or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit())
or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
newelement = float(element)
Run Code Online (Sandbox Code Playgroud)
这是有效的,但显然if语句有点像熊.我考虑的另一个解决方案是将转换包装在try/catch块中,看看它是否成功,如本问题所述.
有没有其他想法?关于分区和try/catch方法的相对优点的意见?
我有许多类似的字符串Current Level: 13.4 db.
,我想提取浮点数.我说漂浮而不是十进制,因为它有时是完整的.RegEx能做到这一点还是有更好的方法?
这实际上是可行的吗?我有一些非常长的正则表达式模式规则很难理解,因为它们不能同时适应屏幕.例:
test = re.compile('(?P<full_path>.+):\d+:\s+warning:\s+Member\s+(?P<member_name>.+)\s+\((?P<member_type>%s)\) of (class|group|namespace)\s+(?P<class_name>.+)\s+is not documented' % (self.__MEMBER_TYPES), re.IGNORECASE)
Run Code Online (Sandbox Code Playgroud)
反斜杠或三重引号不起作用.
编辑.我结束使用VERBOSE模式.以下是正则表达式模式现在的样子:
test = re.compile('''
(?P<full_path> # Capture a group called full_path
.+ # It consists of one more characters of any type
) # Group ends
: # A literal colon
\d+ # One or more numbers (line number)
: # A literal colon
\s+warning:\s+parameters\sof\smember\s+ # An almost static string
(?P<member_name> # Capture a group called member_name
[ #
^: # Match anything but a colon (so finding …
Run Code Online (Sandbox Code Playgroud) 我正在努力将C++程序的一部分转换为Python,但是我在替换C函数strtod时遇到了一些麻烦.我正在处理的字符串由简单的数学方程组成,例如"KM/1000.0".问题是两个常量和数字是混合的,因此我无法使用float().
如何编写Python函数来模拟strtod
哪个函数返回转换后的数字和下一个字符的位置?
如何在任何大字符串中找到最后一个数字?
例如在下面的字符串中我想要47作为输出:
'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'
PS:我们不知道这个数字.47号只是一个例子.它可以是0到900之间的任何数字.
我有一个表格中的字符串列表,如
a = ['str','5','','4.1']
Run Code Online (Sandbox Code Playgroud)
我想将列表中的所有数字转换为浮点数,但保持其余数字不变,就像这样
a = ['str',5,'',4.1]
Run Code Online (Sandbox Code Playgroud)
我试过了
map(float,a)
Run Code Online (Sandbox Code Playgroud)
但显然它给了我一个错误,因为一些字符串不能转换为浮点数.我也试过了
a[:] = [float(x) for x in a if x.isdigit()]
Run Code Online (Sandbox Code Playgroud)
但它只给了我
[5]
Run Code Online (Sandbox Code Playgroud)
所以浮点数和所有其他字符串都会丢失.我该怎么做才能同时保留字符串和数字?
我试图做一些应该非常简单的事情并检查Entry
字段中的值是否是有效和实数.该str.isnumeric()
方法不考虑" - "负数或".".十进制数.
我尝试为此编写一个函数:
def IsNumeric(self, event):
w = event.widget
if (not w.get().isnumeric()):
if ("-" not in w.get()):
if ("." not in w.get()):
w.delete(0, END)
w.insert(0, '')
Run Code Online (Sandbox Code Playgroud)
这可以正常工作,直到你回去并在那里键入字母.然后就失败了.
我研究了使用该.split()
方法的可能性,但我无法找到一个可靠的正则表达式来处理它.
这是一件非常正常的事情.有任何想法吗?
我BeautifulSoup
在 Python 中使用。
我想从网页获取可下载文件的大小。例如,这个页面有一个下载txt
文件的链接(通过点击“保存”)。如何获得该文件的大小(以字节为单位)(最好不下载)?
如果 中没有选项BeautifulSoup
,那么请建议 Python 内外的其他选项。
我试图从Python字符串中的数字中分离出非数字。数字可以包括浮点数。
Original String Desired String
'4x5x6' '4 x 5 x 6'
'7.2volt' '7.2 volt'
'60BTU' '60 BTU'
'20v' '20 v'
'4*5' '4 * 5'
'24in' '24 in'
Run Code Online (Sandbox Code Playgroud)
这是一个很好的关于如何在PHP中实现这一目标的线程:
我想在Python中操纵上述字符串。
以下代码在第一个示例中有效,但在其他示例中无效:
new_element = []
result = [re.split(r'(\d+)', s) for s in (unit)]
for elements in result:
for element in elements:
if element != '':
new_element.append(element)
new_element = ' '.join(new_element)
break
Run Code Online (Sandbox Code Playgroud) 我想找到使用Python 3出现在字符串中的第一个浮点数.
我查看了其他类似的问题,但我无法理解它们,当我尝试实施它们时,它们不适合我的情况.
一个示例字符串
I would like 1.5 cookies please
python ×11
regex ×4
python-3.x ×3
string ×3
alphanumeric ×1
casting ×1
file ×1
formatting ×1
html-parsing ×1
isnumeric ×1
list ×1
parsing ×1
replace ×1
search ×1
size ×1
strtod ×1
validation ×1