简体   繁体   English

如何将字符串中的数字转换为实际数字

[英]How to convert numbers in a string into actual numbers

i have been given a string of numbers and have been tasked to reproduce only the numbers in the string with a funcion that prints within the function which i was able to do with the following. 我被赋予了一个数字字符串,并被赋予只复制字符串中的数字的功能,该函数在我可以进行以下操作的函数中进行打印。

# function that prints, no return the values in list
def reprint (f) :
    for numbers in (f):
        tokens = numbers.split(',')
        for values in tokens :

            print values,
        print


#Main        
stringlist =["1,25,999",
             "123.4,56.7890,13.571",
             "1,23.45,6,7.8"]

reprint (stringlist)

Returns 退货

1 25 999
123.4 56.7890 13.571
1 23.45 6 7.8

The trick though is for floats to print with 2 decimal places and thats where i get stuck. 虽然,技巧是让浮点数以2个小数位打印,这就是我被卡住的地方。 I tried to add something like 我试图添加类似

if '.' in values :
    print "%.2f" % (values)
else print "%d" % (values)

but that didnt work, i get an error saying that print "3%d" % (values) TypeError: %d format: a number is required, not str. 但这没用,我收到一条错误消息,提示打印“ 3%d”%(值)TypeError:%d格式:需要数字,而不是str。 Any ideas on how to get the string treated as numbers? 关于如何将字符串视为数字的任何想法?

EXPECTED Output = 预期输出=

1 25 999
123.40 56.79 13.57
1 23.45 6 7.80

Use ast.literal_eval to convert those strings into tuple of integers and floats and then use isinstance to check whether it's an int or float : 使用ast.literal_eval将这些字符串转换为整数和浮点数的元组,然后使用isinstance检查它是int还是float

>>> from ast import literal_eval
for item in stringlist:
    tup =  literal_eval(item)
    for x in tup:
        if isinstance(x, float):
            print format(x, '.2f'),
        elif isinstance(x, int):
            print format(x, 'd'),
    print
...     
1 25 999
123.40 56.79 13.57
1 23.45 6 7.80

Use float() to convert to float number and int() to convert to an integer one. 使用float()转换为浮点数,使用int()转换为整数1。

if '.' in values :
   print "%.2f" % float(values)
else:
   print "%d" % int(values)

You could replace 您可以更换

print values,

with

if '.' in values:
   print '%.2f' % float(values),
else:
   print values,

You could do something like this: 您可以执行以下操作:

>>> stringlist
['1,25,999', '123.4,56.7890,13.571', '1,23.45,6,7.8']
>>> for line in stringlist:
...     for s in line.split(','):
...         if '.' in s:
...             try:
...                 f=float(s)
...             except ValueError:
...                 print '{} is not a float'
...             else:
...                 print '{:.2f}'.format(f),
...         else:
...             try:
...                 i=int(s)
...             except ValueError:    
...                 print '{} is not an int'.format(s)
...             else:
...                 print i,
...      print

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

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