Python 将字符串中的整数转换为小数
我有一个数学函数字符串,如下所示:Python 将字符串中的整数转换为小数,python,string,integer,Python,String,Integer,我有一个数学函数字符串,如下所示: add(multiply(1, 4461.2419), multiply(subtract(X1, 5), 475.5)) 我只想提取整数并将其转换为小数,然后再将其转换为字符串。例如,我希望输出如下所示: add(multiply(1.0, 4461.2419), multiply(subtract(X1, 5.0), 475.5)) 我该怎么做呢?另外,请注意'X1'是一个变量名,所以我不希望变量名中的1转换为float 到目前为止,我已经尝试过这样的
add(multiply(1, 4461.2419), multiply(subtract(X1, 5), 475.5))
我只想提取整数并将其转换为小数,然后再将其转换为字符串。例如,我希望输出如下所示:
add(multiply(1.0, 4461.2419), multiply(subtract(X1, 5.0), 475.5))
我该怎么做呢?另外,请注意'X1'是一个变量名,所以我不希望变量名中的1转换为float
到目前为止,我已经尝试过这样的方法来识别整数:
s = "add(multiply(1, 4461.2419), multiply(subtract(X1, 5), 475.5))"
print(re.findall("[-+]?\d+", s))
但它给出了这样的结果:
['1', '4461', '2419', '1', '5', '475', '5']
而且似乎也能把小数分开。
谢谢 不太漂亮,但我使用了regex。也许有更好的答案
import re
fnStr = 'add(multiply(1, 4461.2419), multiply(subtract(X1, 5), 475.5))'
# initializing the string to store the final value
finalStr = ''
# looks like it is always going to be that integers will end up as parameters to function calls, so splitting them using commas and looping the parts over
for i in fnStr.split(', '):
# following is for ignoring the floats and also the variables which are of form X1
if '.' in i and not re.search('\w\d',i):
finalStr += i+', '
#This is where we detect the integer and convert in to float and replace the string
else:
finalStr += re.sub('\d',str(float(re.search('\d',i).group(0))), i) +', '
# finally stripping the last comma and space added as a sideeffect of the previous loop
print finalStr.rstrip(', ')
编辑:如果您认为变量可以是任何名称,如XX11
str1= 'add(multiply(1, 4461.2419), multiply(subtract(X1, 5), 475.5))'
def replf(matchobj):
a= matchobj.group(0)
float= re.findall('\d+',a)[0]+'.0'
return re.sub('\d+', float,a)
print re.sub('[\(\,\s](\d+)[\)\,\s]' ,replf,str1) #no decimals allowed
输出:
add(multiply(1.0, 4461.2419), multiply(subtract(X1, 5.0), 475.5))
此正则表达式与您在上文re.findall()中使用的函数相结合,应提供所有数字:
[^a-zA-Z_0-9.]([\d.]+)
它从变量名称中排除数字,例如:
aa123
as_123
AS123_
以及所有其他类似的组合。非常奇怪的变量名可能会导致以下故障:
as%1234
fds$121
asfas#231
如果您计划使用特殊字符命名变量,请将它们添加到括号中。一旦你得到了所有的数字,你应该能够将它们转换成浮点,并且不费吹灰之力地附加它们。你能告诉我你到现在为止都尝试了什么吗?你能添加一段代码和错误(如果有)吗?试试正则表达式。看看我到目前为止有什么。谢谢你的调查。