This answer draws on the one by Alex J Best for defining f,
but also defines g.
Define a multivariate polynomial ring and its generator tuple:
sage: R = PolynomialRing(QQ, 'a', 4)
sage: R
Multivariate Polynomial Ring in a0, a1, a2, a3 over Rational Field
sage: a = R.gens()
sage: a
(a0, a1, a2, a3)
Consider one of the generators (or "indeterminates", or "variables"):
sage: p = a[2]
sage: p
a2
To get its index in the generator tuple:
sage: a.index(p)
2
This can be made into the function f requested in the question:
sage: f = a.index
sage: f(p)
2
The above is tied to the definition of a; more generally:
def f(p):
r"""
Return the index of this generator of a polynomial ring.
"""
return p.parent().gens().index()
What function g the question requests is not entirely clear.
If we want g(a[2]) to return the string 'a':
def g(p):
r"""
Return the generator name stripped of its index.
"""
return ''.join(c for c in str(p) if not c.isdigit())
With that definition:
sage: p = a[2]
sage: aa, k = g(p), f(p)
sage: aa
'a'
sage: k
2
sage: ak = aa + str(k)
sage: ak
'a2'
sage: ak == str(p)
True
sage: R(ak) == p
True
If instead we want g(a[2]) to return the tuple R.gens():
def g(p):
r"""
Return the tuple of generators of the parent polynomial ring.
"""
return p.parent().gens()
With that definition:
sage: p = a[2]
sage: aa, k = g(p), f(p)
sage: aa
(a0, a1, a2, a3)
sage: k
2
sage: ak = aa[k]
sage: ak
a2
sage: ak == p
True