[英]String formatting : Replace “%0 %1 %2” with tuple with 0,1,2 indexes
我是python的初學者。 我在python中發現了一個問題,即給定格式為“%0的字符串是%1%2”和一個元組(“ Ram”,“ good”,“ boy”)。 表示字符串包含%x,應將其替換為索引x的相應元組元素。 (編輯后):忘了提及,如果給定的元組為(“ Ram”,“ good”)。,答案必須為“ Ram是一個好%2”,即剩余的%x應該保留原樣
結果必須是“ Ram是個好男孩”。 我是這樣做的(下面是代碼)。 但是我知道,可以用更有效的方式編寫代碼,而不必擔心。 行...您能幫忙嗎? 提前致謝
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+
匹配一個百分號后跟1個或多個數字,lambda中的x
是一個匹配對象,我們使用.group
從中獲取匹配的字符串,並僅將{}
包裹數字字符串的數字切成數字以用作占位符對於str.format
。
重新評論說,您可以擁有比args更多的占位符,sub進行最大替換count
arg count
:
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 and join:
print(" ".join(["{"+w[1:]+"}" if w[0] == "%" else w for w in s.split(" ")]).format(*args))
three and two and one
使用內置的字符串格式。
>>> print('%s is a %s %s' % ('Ram','good','boy'))
Ram is a good boy
根據您的編輯,您正在尋找與眾不同的東西。 您可以使用re.findall
和re.sub
完成此操作:
>>> import re
>>> formatstring,args = "%0 is a %1 %2",("Ram", "good", "boy")
>>> for x in re.findall('(%\d+)',formatstring):
formatstring = re.sub(x,args[int(x[1:])],formatstring)
>>> formatstring
'Ram is a good boy'
也許使用string.replace
來將各種%x
替換為與它們對應的元組,例如:
format = "%0 is a %1 %2"
args = ("Ram", "good", "boy")
result = format # Set it here in case args is the empty tuple
for index, arg in enumerate(args):
formatter = '%' + str(index) # "%0", "%1", etc
result = result.replace(formatter, arg)
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.