将带括号的字符串转换为整数- %d 格式:需要数字,而不是 str'
convert a string with parenthesis to an integer- %d format: a number is required, not str'
我是 Python 的新手。我正在尝试将公式插入 excel 列。公式的输入不一定来自一行。我有-
formula= '=B4-(28.471-0.0146*B4+0.0008*B4^2)+D2'
formulaRegex= re.compile(r'([A-Z]+)(\d{1,})')
cellCoordinatesR= formulaRegex.findall(formula) #find a Cap. Letter and a number
rowIndex=[] #list of the row indexes i.e '4' in 'B4' and '2' in 'D2'
for group in cellCoordinatesR:
rowIndex.append(group[1])
rowIndexFormat= '('+','.join(rowIndex)+')' # add parenthesis to rowIndex list
'(4,4,4,2)'
newFormula= formulaRegex.sub(r'%d',formula) %rowIndexFormat
错误:
'%d format: a number is required, not str'
我想要的:
newFormula= formulaRegex.sub(r'%d',formula) %(4,4,4,2)
我目前拥有的:
newFormula= formulaRegex.sub(r'%d',formula) %'(4,4,4,2)'
我找到了解决这个问题的方法:
newFormula= formulaRegex.sub(r'%d',formula) %
(int(rowIndex[0]),int(rowIndex[1]), int(rowIndex[2]), int(rowIndex[3]))
'=B4-(28.471-0.0146*B4+0.0008*B4^2)+D2'
但它要求我根据需要多次 int(rowIndex[i])
。我怎样才能拥有 %d
而不必多次键入 int(rowIndex[i])
?
您可以将 int
应用于序列中的项目,而不是一次一个。
... % tuple(int(i) for i in rowIndex)
但是,鉴于问题是字符串中有整数,为什么不使用 %s
占位符而不是 %d
将它们插入为字符串?
我是 Python 的新手。我正在尝试将公式插入 excel 列。公式的输入不一定来自一行。我有-
formula= '=B4-(28.471-0.0146*B4+0.0008*B4^2)+D2'
formulaRegex= re.compile(r'([A-Z]+)(\d{1,})')
cellCoordinatesR= formulaRegex.findall(formula) #find a Cap. Letter and a number
rowIndex=[] #list of the row indexes i.e '4' in 'B4' and '2' in 'D2'
for group in cellCoordinatesR:
rowIndex.append(group[1])
rowIndexFormat= '('+','.join(rowIndex)+')' # add parenthesis to rowIndex list
'(4,4,4,2)'
newFormula= formulaRegex.sub(r'%d',formula) %rowIndexFormat
错误:
'%d format: a number is required, not str'
我想要的:
newFormula= formulaRegex.sub(r'%d',formula) %(4,4,4,2)
我目前拥有的:
newFormula= formulaRegex.sub(r'%d',formula) %'(4,4,4,2)'
我找到了解决这个问题的方法:
newFormula= formulaRegex.sub(r'%d',formula) %
(int(rowIndex[0]),int(rowIndex[1]), int(rowIndex[2]), int(rowIndex[3]))
'=B4-(28.471-0.0146*B4+0.0008*B4^2)+D2'
但它要求我根据需要多次 int(rowIndex[i])
。我怎样才能拥有 %d
而不必多次键入 int(rowIndex[i])
?
您可以将 int
应用于序列中的项目,而不是一次一个。
... % tuple(int(i) for i in rowIndex)
但是,鉴于问题是字符串中有整数,为什么不使用 %s
占位符而不是 %d
将它们插入为字符串?