我想在每秒钟的逗号中添加字符串@



我想将'a,b,c,d,e,f,g,e'更改为'a,b@c,d@e,f@g,e'

输入:

'a,b,c,d,e,f,g,e'

输出:

'a,b@c,d@e,f@g,e'

有可能吗?

对于正则表达式爱好者:

import re
input = 'a,b,c,d,e,f,g,e'
output = re.sub(r',([^,]*),', r',1@', input)

您可以尝试一下,尽管它有点复杂:

a = 'a,b,c,d,e,f,g,e'
l = a.split(',')
res=''.join([i+',' if num%2==0 else i+'@' for num,i in enumerate(l)]).strip('@').strip(',')

是的,这是可能的,这里有另一种方法,只需要创建一个新字符串,并根据条件更改添加的内容。

def func(s):
    res = ''
    i = 0
    for c in s:
        if c == ',':
            i += 1
        res += '@' if c == ',' and i % 2 == 0 else c
    return res
>>> a = 'a,b,c,d,e,f,g,e'
>>> func(a)
'a,b@c,d@e,f@g,e'

试试这个-

    >>> a = 'a,b,c,d,e,f,g,e'
    >>> z=','.join([val if (idx)%2!=0 else '@'+val for idx,val in enumerate(a.split(','))]).replace('@','',1).replace(',@','@')
    >>> print z
    >>> a,b@c,d@e,f@g,e

您可以很容易地使用阶梯切片、zipstr.join来实现这一点。

a = 'a,b,c,d,e,f,g,e'
pairs = zip(a.split(',')[::2], a.split(',')[1::2])
print '@'.join(','.join(p) for p in pairs)
# a,b@c,d@e,f@g,e

这假设有奇数个逗号,并且"对"是由@划分的(如注释中所述)。

a = 'a,b,c,d,e,f,g,e'

b = a.split(',')
it = iter(b[ 1: -1])
result = []
while True:
    try:
        result.append("{0}@{1}".format(next(it), next(it)))
    except StopIteration:
        break
print(",".join([b[0]] + result + [b[-1]]))

输出:

a,b@c,d@e,f@g,e

最新更新