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

2024-10-01 15:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

字符串包含句子和数字,可以是浮点或整数。我试图给每个数字加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}')

Tags: 字符串innewfor数字整数ch句子
2条回答

完成此任务的一种方法是使用regex


示例1:

提取并向数值中添加1

import re

nums = re.findall(r'(\d+(?:\.\d+)?)', s)

[int(i) + 1 if i.isdigit() else float(i) + 1 for i in nums]

说明:

  • 使用正则表达式将所有数值提取到一个list中,带或不带小数
  • 使用列表理解为每个数字加1,根据存在或小数点,将其转换为floatint

正则表达式:
这里使用的正则表达式模式提取任何单个或重复的数字,如\d+。此外,还有一个可选的非捕获组(?:\.\d+)?),用于捕获小数点和小数点后的任何数字,并将该组包括在原始组中,而不是其他组中

输出:

[13, 33, 7.326, 8.498000000000001, 6.8, 4, 8749, 235.0, 4, 3]

例2:

将原始字符串中的数值替换为数值+1

下面的算法遵循与示例1中解释的相同逻辑;正在构造一个新列表,以包含字符串中更新的数值

import re

exp = re.compile(r'(\d+(?:\.\d+)?)')
r = []

for i in re.split(' |\n', s):
    if re.match(exp, i):
        i = int(i) + 1 if i.isdigit() else float(i) + 1
    r.append(str(i))

输出:

>>> ' '.join(r)

'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' 

使用split()将字符串拆分为项目。每个项目表示一个string、一个float或一个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 

相关问题 更多 >

    热门问题