简体   繁体   English

Python中的文字字符串替换

[英]Literal String substitution in python

Consider the below code snippet in python 考虑下面的python代码片段

argKey = 'actualArgument'

methodA(argKey=argVal) #invoking methodA

where methodA() is defined as : 其中methodA()定义为:

def methodA(actualArgument, actualArgument2, actualArgument3)

methodA can be invoked only via named arguments ie. methodA只能通过命名参数(即)来调用。 you invoke by specifying the argument name and passing the argument value. 您可以通过指定参数名称并传递参数值来调用。

--> throws an error : ->引发错误:

TypeError: methodA() got an unexpected keyword argument 'argKey '

I want 'methodA' to be invoked by the value contained in the 'argKey' variable ie 我希望由“ argKey”变量中包含的值调用“ methodA”,即

methodA(actualArgument=argVal)

How to get the substitution of the string into the method invocation call.? 如何将字符串替换成方法调用。

To pass parameters with computed names, use a dict: 要传递带有计算名称的参数,请使用字典:

def foo(a, b):
  return a+b

name_of_a = 'a'
params = {name_of_a: 1, 'b': 2}
print foo(**params) # note the asterisks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM