我需要将任意字符串转换为 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) + '_'
这是一种非常幼稚的方法。我需要检查字符串是否包含无效的变量名字符并将它们替换为 ''
什么是pythonic方式来做到这一点?
最佳答案
好吧,我想最好的 Triptych 的解决方案是......单线!
>>> def clean(varStr): return re.sub('\W|^(?=\d)','_', varStr)
...
>>> clean('32v2 g #Gmw845h$W b53wi ')
'_32v2_g__Gmw845h_W_b53wi_'
此替换用下划线替换任何非可变的适当字符,如果字符串以数字开头,则在前面插入下划线。 IMO,'name/with/slashes' 作为变量名 name_with_slashes
看起来比 namewithslashes
更好。
关于python - 如何在 Python 中将字符串转换为有效的变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3303312/