Reputation: 226712
In R, the get(s)
function retrieves the value of the symbol whose name is stored in the character variable (vector) s
, e.g.
X <- 10
r <- "XVI"
s <- substr(r,1,1) ## "X"
get(s) ## 10
takes the first symbol of the Roman numeral r
and translates it to its integer equivalent.
Despite spending a while poking through R-Python dictionaries and Googling various combinations of "metaprogramming", "programming on the language", "symbol", "string", etc., I haven't come up with anything. (I am a very experienced R user and a novice Python user.)
(I know the example above is a (very!) poor way to approach the problem. I'm interested in the general answer to this question, not specifically in converting Roman numerals to integers ...)
Upvotes: 16
Views: 3921
Reputation: 27220
You can use locals
:
s = 1
locals()['s']
EDIT:
Actually, get
in R is more versatile - get('as.list')
will give you back as.list
. For class members, in Python, we can use getattr
(here), and for built-in things like len
, getattr(__builtins__, 'len')
works.
Upvotes: 17
Reputation: 4261
Use the eval
function, which evaluates a string as an expression.
X = 10
r = "XVI"
v = eval(r[0])
Important note: eval()
evaluates any code that can be used in an expression, not just variables. Do not use it directly in conjunction with user input, which could risk a security vulnerability.
Upvotes: 6