有条件地格式化字符串 - Python

时间:2016-02-09 06:42:37

标签: python string str-replace

我想获取一个字符串并对其进行格式化,以便我可以控制我所做的更改次数。例如..

“这是一个很棒的字符串”,替换方法“@”表示“a”会给我...

“这是@n @wesome字符串”但是我想说用“@”代替1“a”并留下其余部分..

“这是@n awesome string”允许放置是随机的,但重要的是我考虑了我替换了多少特定类型。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

字符串替换函数采用可选的count参数来控制要进行的最大替换次数

"This is an awesome string".replace("a","@")   # "This is @n @wesome string"

"This is an awesome string".replace("a","@",1) # "This is @n awesome string"

如果您需要随机执行此操作,我们可以编写一个函数来执行此操作

import random
def randreplace(str,c,c_replace,maxnum=0):
    if maxnum >= str.count(c) or maxnum<1:
        return str.replace(c,c_replace)
    indices = [i for i,x in enumerate(str) if x==c]
    replacements = random.sample(indices,maxnum)
    st_pieces = (x if not i in replacements else c_replace for i,x in enumerate(str))
    return "".join(st_pieces)

此函数使用字符串来替换,要替换的字符,替换它的字符以及最大替换次数(0表示所有替换)并返回完成所需替换次数的字符串随意。

random.seed(100)
randreplace("This is an awesome string","a","@",1) # "This is @n awesome string"
randreplace("This is an awesome string","a","@",1) # "This is an @wesome string"
randreplace("This is an awesome string","a","@",2) # "This is @n @wesome string"
randreplace("This is an awesome string","a","@")   # "This is @n @wesome string"

答案 1 :(得分:1)

以下功能可让您更改单个匹配字符:

def replace_a_char(text, x, y, n):
    matched = 0
    for index, c in enumerate(text):
        if c == x:
            matched += 1
            if matched == n:
                return text[:index] + y + text[index+1:]

    return text

text = "This is an awesome string and has lot of characters"

for n in xrange(1, 10):
    print replace_a_char(text, 'a', '@', n)

给你以下输出:

This is @n awesome string and has lot of characters
This is an @wesome string and has lot of characters
This is an awesome string @nd has lot of characters
This is an awesome string and h@s lot of characters
This is an awesome string and has lot of ch@racters
This is an awesome string and has lot of char@cters
This is an awesome string and has lot of characters
This is an awesome string and has lot of characters
This is an awesome string and has lot of characters

答案 2 :(得分:1)