如何将字符串转换为有效的Python变量名?

36 投票
4 回答
17174 浏览
提问于 2025-04-16 01:39

我需要把一个随便的字符串转换成一个在Python中有效的变量名。

这里有一个非常简单的例子:

s1 = 'name/with/slashes'
s2 = 'name '

def clean(s):
    s = s.replace('/', '')
    s = s.strip()

    return s

# the _ is there so I can see the end of the string
print clean(s1) + '_'

这个方法太简单了。我需要检查这个字符串里有没有不合法的变量名字符,并把它们替换掉。

有没有什么更符合Python风格的方法来做到这一点?

4 个回答

5

你可以使用内置的函数:str.isidentifier(),结合filter()来实现这个功能。这样做不需要导入像re这样的库,它的工作原理是逐个检查每个字符,如果这个字符是一个合法的标识符,就把它返回。然后你只需要用''.join把这些字符重新组合成一个字符串。

s1 = 'name/with/slashes'
s2 = 'name '

def clean(s):
    s = ''.join(filter(str.isidentifier, s))
    return s

print f'{clean(s1)}_' #the _ is there so I can see the end of the string

编辑:

如果你像Hans Bouwmeester在回复中提到的那样,想要把数字也包括进来,你可以创建一个lambda函数,使用isIdentifierisdecimal这两个函数来检查字符。显然,这个方法可以根据你的需要进行扩展。代码如下:

s1 = 'name/with/slashes'
s2 = 'name i2, i3    '
s3 = 'epng2 0-2g [ q4o 2-=2 t1  l32!@#$%*(vqv[r 0-34 2]] '

def clean(s):
    s = ''.join(filter( 
        lambda c: str.isidentifier(c) or str.isdecimal(c), s))
    return s
#the _ is there so I can see the end of the string
print(f'{ clean(s1) }_')
print(f'{ clean(s2) }_')
print(f'{ clean(s3) }_')

结果是:

namewithslashes_
namei2i3_
epng202gq4o22t1l32vqvr0342_
73

好吧,我想用一句话来超越Triptych的解决方案!

>>> def clean(varStr): return re.sub('\W|^(?=\d)','_', varStr)
...

>>> clean('32v2 g #Gmw845h$W b53wi ')
'_32v2_g__Gmw845h_W_b53wi_'

这个替换方法会把任何不适合做变量名的字符换成下划线,并且如果字符串是以数字开头的,还会在前面加一个下划线。在我看来,'name/with/slashes' 作为变量名 name_with_slashes 看起来比 namewithslashes 更好。

39

根据Python的定义,标识符是以字母或下划线开头,后面可以跟任意数量的字母、数字和下划线:

import re

def clean(s):

   # Remove invalid characters
   s = re.sub('[^0-9a-zA-Z_]', '', s)

   # Remove leading characters until we find a letter or underscore
   s = re.sub('^[^a-zA-Z_]+', '', s)

   return s

使用方法如下:

>>> clean(' 32v2 g #Gmw845h$W b53wi ')
'v2gGmw845hWb53wi'

撰写回答