简体   繁体   English

捕获科学记数法并转换为字符串

[英]Capture scientific notation and covert to string

I need to capture occurrences of scientific notation in a string and convert the notation in string format using python.我需要在字符串中捕获科学记数法的出现,并使用 python 将记数法转换为字符串格式。

eg E-100 and/or e-100 should be represented as 1E-100 in string format.例如,E-100 和/或 e-100 应以字符串格式表示为 1E-100。

So far I have following code到目前为止,我有以下代码

>>> import re
>>> num = "My numbers are E-100 and e-100"
>>> print(num)

My numbers are E-100 and e-100我的号码是 E-100 和 e-100

>>> re.findall('[eE]?[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', num)

['E-100', 'e-100'] ['E-100','e-100']

This prints numbers as a list.这会将数字打印为列表。

How can I convert each of this number to 1E-100 and print in string format.如何将此数字中的每一个转换为 1E-100 并以字符串格式打印。

Update: This should work with all numbers eg 2e-123 should be represented in string format as 2E-123更新:这应该适用于所有数字,例如 2e-123 应该以字符串格式表示为 2E-123

Thanks in advance !!提前致谢 !!

You can use replace operation.您可以使用替换操作。

Code:代码:

import re
num = "My numbers are E-100, e-100, e+07, E-234, 2e-09 "
arr = re.findall('[eE]?[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?', num)

for i in range(len(arr)):
    arr[i] = arr[i].replace('e', 'E')
    if arr[i][0] == 'E':
        arr[i] = arr[i].replace('E', '1E')

print(arr)

Output: Output:

['1E-100', '1E-100', '1E+07', '1E-234', '2E-09']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM