我正在尝试将字符串转换为整数,但是这并不是我想的那么容易。
content = '''
<entry colname="1" morerows="1" morerowname="2"><p>111</p></entry>
<entry colname="2" rowname="2"><p></p></entry>'''
morerows = ''.join(re.findall('morerows="\d"', content))
morerows_n = int(''.join(re.findall('\d', morerows)))
print(morerows_n)
这将导致如下错误:
morerows_n = int(''.join(re.findall('\d', morerows)))
ValueError: invalid literal for int() with base 10: ''
该代码哪里出问题了? 我已经尝试过int()函数,但是不起作用,它也不浮动。
有什么帮助吗?
答案 0 :(得分:1)
在您的实际情况下,我想morerows属性中包含非整数字符。
How about this:
content = '''
<entry colname="1" morerows="1x" morerowname="2"><p>111</p></entry>
<entry colname="1" morerows="1" morerowname="2"><p>111</p></entry>
<entry colname="2" rowname="2"><p></p></entry>'''
morerows = ''.join(re.findall('morerows="[0-9]+"', content))
if morerows:
morerows_n = int(''.join(re.findall('\d', morerows)))
print(morerows_n)
使用[0-9]+
代替\d