当前位置:  开发笔记 > 编程语言 > 正文

字符串格式:将"%0%1%2"替换为带有0,1,2索引的元组

如何解决《字符串格式:将"%0%1%2"替换为带有0,1,2索引的元组》经验,为你挑选了1个好方法。



1> Padraic Cunn..:

我会用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+匹配百分号后跟一个或多个数字,xlambda中的匹配对象是我们用来.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 

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有