python - 字符串格式 : Replace "%0 %1 %2" with tuple with 0, 1,2 索引

标签 python string string-formatting

我是 python 初学者。我在 python 中发现了一个问题,即 Given string in format "%0 is a %1 %2"and a tuple ("Ram", "good", "boy").表示字符串包含 %x,其中应将其替换为索引 x 的相应元组元素。 (编辑后):忘了提,如果给定的元组是(“Ram”,“good”)。,答案必须是“Ram is a good %2”,即剩余的 %x 应该保持原样

结果一定是“Ram is a good boy”。我是这样做的(下面是代码)。但我开始知道它可以用更有效的方式编写,而不是。线路......你能帮忙吗?提前致谢

format = "%0 is a %1 %2"
args = ("Ram", "good", "boy")
count = 0
for i in range(0, len(format) + 1):
    if format[i] == '%':
        b= '%'
        b = b + format[i + 1]

        format = format.replace(b, args[int(format[i+1])])
        count+= 1

        if count == len(args):
            break

print format

最佳答案

我会使用str.format,你可以简单地解压元组:

args = ("Ram", "good", "boy")


print("{}  is a {} {}".format(*args))
Ram is  a good boy

如果您需要先操作原始字符串,请使用 re.sub :

import re

"%2 and %1 and %0"
 args = ("one", "two", "three")

print(re.sub(r"%\d+", lambda x: "{"+x.group()[1:]+"}", s).format(*args))

输出:

In [6]: s = "%2 and %1 and %0"

In [7]: re.sub(r"%\d+", lambda x: "{"+x.group()[1:]+"}", s).format(*args)
Out[7]: 'three and two and one'

In [8]: s = "%1 and %0 and %2"

In [9]: re.sub(r"%\d+",lambda x: "{"+x.group()[1:]+"}", s).format(*args)
Out[9]: 'two and one and three'

%\d+ 匹配百分号后跟一位或多位数字,lambda 中的 x 是我们使用的匹配对象 .group{} 中获取匹配的字符串并仅切分包裹数字字符串的数字,以用作 str.format 的占位符。

重新评论你可以有比 args 更多的占位符,sub 需要一个 count arg 的最大替换数量:

s = "%0 is a %1 %2"
args = ("Ram", "Good")
sub = re.sub(r"%\d+\b", lambda x: "{"+x.group()[1:]+"}", s,count=len(args)).format(*args)

print(sub)

输出:

Ram is a Good %2

要为任意顺序工作,需要更多的逻辑:

s = "%2 is a %1 %0"
args = ("Ram", "Good")

sub = re.sub(r"%\d+\b", lambda x: "{"+x.group()[1:]+"}" if int(x.group()[1:]) < len(args) else x.group(), s).format(*args)

print(sub)

输出:

%2 is a Good Ram

将 lambda 逻辑移到函数中会更好一些:

s = "%2 is a %1 %0"
args = ("Ram", "Good")
def f(x):
    g = x.group()
    return "{"+g[1:]+"}" if int(x.group()[1:]) < len(args) else g

sub = re.sub(r"%\d+\b",f,  s).format(*args)

或者如果占位符总是独立的,则使用 split 和 join:

print(" ".join(["{"+w[1:]+"}" if w[0] == "%" else w for w in s.split(" ")]).format(*args))

three and two and one 

关于python - 字符串格式 : Replace "%0 %1 %2" with tuple with 0, 1,2 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275831/

相关文章:

python - 将两个日期时间连接成字符串日期范围

python - 如何使用python将带有分隔符的字符串格式化为列

c++:使用X Macro在类中定义枚举和字符串数组?

python - 有没有一种简单而漂亮的方法可以将列表中的项目转换为不同的类型?

python - 一个简单例子的空间复杂度

python - 编写一个名为 filter_out() 的函数,该函数将整数列表作为输入,并返回仅保留数字过滤的列表

python - 如何根据给定条件交换字符串的字符?

python - 在python中删除指数格式的前导0

python - 将 Python 字符串格式化与列表一起使用

python - 如何使用 Mediapipe Pose 更改输出视频上的跟踪点和连接线的颜色?