用给定的字符串替换字符串的字符

时间:2018-08-22 01:42:37

标签: python string

给出此字符串'www__ww_www _'

我需要用以下字符串“ 1234”中的CHARACTERS替换所有_。因此结果应该是“ www12ww3www4”

TEXT = 'aio__oo_ecc_'
INSERT = '1234'

insert = list(INSERT)
ret = ''

for char in TEXT:
    if char == '_':
        ret += insert[0]
        insert.pop(0)
    else:
        ret += char

print (ret)
>> aio12oo3ecc4

正确的方法是什么?因为这似乎是效率最低的方法。

4 个答案:

答案 0 :(得分:3)

您可以在其中使用string iterator and a generator expressionternary

TEXT = 'aio__oo_ecc_'
INSERT = '1234'

it = iter(INSERT)
print("".join(next(it) if x == "_" else x for x in TEXT))

答案 1 :(得分:2)

如评论中所指出的,您可以直接使用str.replace

for c in INSERT:
    TEXT = TEXT.replace('_', c, 1)

您也可以使用正则表达式替换:

import re
for c in INSERT:
    TEXT = re.sub('_', c, TEXT, 1)

请参阅此处:https://docs.python.org/3/library/re.html

答案 2 :(得分:1)

考虑用下划线分割模式字符串,并用插入字符串压缩它:

TEXT = 'aio__oo_ecc_a' # '_a' added to illustrate the need for zip_longest
from itertools import zip_longest, chain
''.join(chain.from_iterable(zip_longest(TEXT.split('_'), INSERT, fillvalue='')))
#'aio12oo3ecc4a'

zip_longest用于代替“正常” zip,以确保模式的最后一个片段(如果有的话)不会丢失。

分步探索:

pieces = TEXT.split('_')
# ['aio', '', 'oo', 'ecc', 'a']
mix = zip_longest(pieces, INSERT, fillvalue='')
# [('aio', '1'), ('', '2'), ('oo', '3'), ('ecc', '4'), ('a', '')]
flat_mix = chain.from_iterable(mix)
# ['aio', '1', '', '2', 'oo', '3', 'ecc', '4', 'a', '']
result = ''.join(flat_mix)

速度比较:

  1. 此解决方案:每个循环1.32 µs±9.08 ns
  2. 迭代器+三元+列表理解:每个循环1.77 µs±20.8 ns
  3. 原始解决方案:每个回路2 µs±13.2 ns
  4. 环路+正则表达式解决方案:每个环路3.66 µs±103 ns

答案 3 :(得分:0)

您可以在re.sub的替换函数中使用迭代器:

import re
TEXT = 'aio__oo_ecc_'
INSERT = '1234'
i = iter(INSERT)
print(re.sub('_', lambda _: next(i), TEXT))

这将输出:

aio12oo3ecc4
相关问题