如果前四个字符是数字,则在字符串中插入字符

问题描述 投票:0回答:2

我有一个字符串,每次有一个数字时都没有空格。我想创建它并添加一个逗号。

例如,以下内容:

2013 Presidential2008 Presidential2016 Parliamentary - Majoritarian Runoff2016 Parliamentary - Majoritarian Rerun

将转换为:

2013 Presidential, 2008 Presidential, 2016 Parliamentary - Majoritarian Runoff2016 Parliamentary - Majoritarian Rerun

直到现在我有:

for char in s:
...     if char.isalpha():
            ???

我也尝试过使用Javascript:

function isNumber(c) {
    return (i >= '0' && i <= '9');
}
for (var x = 0; x < text.length; x++)
{
    var c = text.charAt(x);
    if isNumber(i){
        // add a ", " before and move to the next char which is a letter
        text[:x] + ', ' + text[x:]
    }   
}

但返回:Uncaught SyntaxError: Unexpected identifier

javascript python python-3.x string
2个回答
3
投票

查看string.prototype.replacemdn)。

let input = '2013 Presidential2008 Presidential2016 Parliamentary - Majoritarian Runoff2016 Parliamentary - Majoritarian Rerun'

//           replace:   (non-digit)(digit)
let output = input.replace(/([^\d])(\d)/g, '$1, $2');
//                           with:   non-digit, digit

console.log(output);

如果您输入的数字后面已经有一个空格,那么可以通过稍微修改正则表达式来确保不要在其中添加逗号:

let input = '1 noSpace2 space 3';

//  replace:   (non-digit nor space)(digit)
let output = input.replace(/([^\d ])(\d)/g, '$1, $2');
//                           with:   non-digit, digit

console.log(output);

1
投票

在Python上使用正则表达式:

import re

text = '2013 Presidential2008 Presidential2016 Parliamentary - Majoritarian Runoff2016 Parliamentary - Majoritarian Rerun'

pat = re.compile(r'([^\d\s])(\d+)')
pat.sub(r'\1, \2', text)

输出:

'2013 Presidential, 2008 Presidential, 2016 Parliamentary - Majoritarian Runoff, 2016 Parliamentary - Majoritarian Rerun'

示例:https://regex101.com/r/tDdfsc/1

© www.soinside.com 2019 - 2024. All rights reserved.