Python:从字符串中提取数字值,并将每个值加1

埃勒姆·亚

字符串包含句子和数字,可以是浮点数或整数。我正在尝试为每个数字加1,然后用字符串中的新数字替换以前的数字。

我编写的代码仅对浮点数加1,而整数保持不变。

s = """helllo everyone 12 32 how 6.326 is a going?
well 7.498 5.8 today Im going 3 to talk 8748 234.0 about
python 3 and compare it with python 2"""

newstr = ''.join((ch if ch in '0123456789.' else ' ') for ch in s)
print(newstr)

listOfNumbers = [float(i) for i in newstr.split()]
#print(f'list of number= {listOfNumbers}')

new_str = s
for digit in listOfNumbers:
    New_digit = digit+1
    print (New_digit)
    new_str = new_str.replace(str(digit),str(New_digit))
print(f'new_str = {new_str}')
确认

使用split()字符串分割成项目。每个项目代表a string,afloat或a int如果是string,则无法将其转换为数字并递增。如果float成功转换为,则可能仍然是int,因此我们尝试将“进一步”转换。

该代码仍然需要处理浮点舍入问题-请参见输出。

def increment_items(string):
    '''Increment all numbers in a string by one.'''
    items = string.split()

    for idx, item in enumerate(items):
        try:
            repl = False
            nf = float(item)
            repl = nf + 1  # when we reach here, item is at least float ...
            ni = int(item)  # ... but might be int - so we try
            repl = ni + 1  # when we reach here, item is not float, but int
            items[idx] = str(repl)
        except ValueError:
            if repl != False:
                items[idx] = str(repl)  # when we reach here, item is float
    return " ".join(items)

s = "helllo everyone 12 32 how 6.326 is a going?\
 well 7.498 5.8 today Im going 3 to talk 8748 234.0 about\
 python 3 and compare it with python 2"


print('Input:', '\n', s, '\n')
result = increment_items(s)
print('Output:', '\n', result, '\n')

输入:

helllo everyone 12 32 how 6.326 is a going? well 7.498 5.8 today Im going 3 to talk 8748 234.0 about python 3 and compare it with python 2

输出:

helllo everyone 13 33 how 7.326 is a going? well 8.498000000000001 6.8 today Im going 4 to talk 8749 235.0 about python 4 and compare it with python 3 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章