sprintf("Hello %s, my name is %s.", "World", "RainDu")
#'Hello World, my name is RainDu.'
pystr_format("Hello {1}, my name is {2}.", "World", "RainDu")
#'Hello World, my name is RainDu.'
以上两句等价。
以上方法在Python中应该写成如下两种形式:
print("Hello %s, my name is %s." % ("World", "RainDu"))
#Hello World, my name is RainDu.
print("Hello {0}, my name is {1}.".format("World", "RainDu"))
#Hello World, my name is RainDu.
pystr_format("Hello {thing}, my name is {name}.", thing="World", name="RainDu")
pystr_format("Hello {thing}, my name is {name}.", c(thing="World", name="RainDu"))
pystr_format("Hello {thing}, my name is {name}.", list(thing="World", name="RainDu"))
#'Hello World, my name is RainDu.'
print("Hello {thing}, my name is {name}.".format(thing = "World",name = "RainDu"))
Hello World, my name is RainDu.
my_cars <- data.frame(car=rownames(mtcars), mtcars)
pystr_format("The {car} gets {mpg} mpg (hwy) despite having {cyl} cylinders.", my_cars)
借助R语言中函数强大的向量化功能,pystr_format函数可以很容易的实现批量化插入特定字符。
supers <- data.frame(
first=c("Bruce", "Hal", "Clark", "Diana"),
last=c("Wayne", "Jordan", "Kent", "Prince"),
is=c("Batman", "Green Lantern", "Superman", "Wonder Woman")
)
pystr_format("{first} {last} is really {is} but you shouldn't call them {first} in public.", supers)
strword = []
for first,last,the in zip(supers["first"],supers["last"],supers["the"]):
print("{0:s} {1:s} is really {2:s} but you shouldn't call them {1:s} in public.".format(first,last,the))
strword.append("{0:s} {1:s} is really {2:s} but you shouldn't call them {1:s} in public.".format(first,last,the))
Bruce Wayne is really Batman but you shouldn't call them Wayne in public.
Hal Jordan is really Green Lantern but you shouldn't call them Jordan in public.
Clark Kent is really Superman but you shouldn't call them Kent in public.
Diana Prince is really Wonder Woman but you shouldn't call them Prince in public.
使用列表表达式进行格式化:
supers["strword"] = ["{0:s} {1:s} is really {2:s} but you shouldn't call them {1:s} in public.".format(first,last,the) for first,last,the in zip(supers["first"],supers["last"],supers["the"])]
{'first': ['Bruce', 'Hal', 'Clark', 'Diana'],
'last': ['Wayne', 'Jordan', 'Kent', 'Prince'],
'strword': ["Bruce Wayne is really Batman but you shouldn't call them Wayne in public.", "Hal Jordan is really Green Lantern but you shouldn't call them Jordan in public.", "Clark Kent is really Superman but you shouldn't call them Kent in public.", "Diana Prince is really Wonder Woman but you shouldn't call them Prince in public."], 'the': ['Batman', 'Green Lantern', 'Superman', 'Wonder Woman']}
使用高阶函数+匿名函数进行格式化
func = lambda x,y,z:"{0:s} {1:s} is really {2:s} but you shouldn't call them {0:s} in public.".format(x,y,z)
supers["strword2"] = list(map(func,supers["first"],supers["last"],supers["the"]))