如何在python中将字符串转换为有效的变量名? [英] how do I convert a string to a valid variable name in python?
本文介绍了如何在python中将字符串转换为有效的变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将任意字符串转换为python中有效变量名的字符串.
这是一个非常基本的例子:
s1 = 'name/with/slashes's2 = '姓名'定义清洁:s = s.replace('/','')s = s.strip()返回print clean(s1)+'_'#the _ is there所以我可以看到字符串的结尾
这是一种非常幼稚的方法.我需要检查字符串是否包含无效变量名字符并替换为 ''
pythonic 的方法是什么?
解决方案
根据 Python,标识符是一个字母或下划线,后跟无限的字母、数字和下划线组成的字符串:
导入重新定义清洁:# 删除无效字符s = re.sub('[^0-9a-zA-Z_]', '', s)# 删除前导字符,直到找到字母或下划线s = re.sub('^[^a-zA-Z_]+', '', s)返回
像这样使用:
<预><代码>>>>干净('32v2 g #Gmw845h$W b53wi')'v2gGmw845hWb53wi'I need to convert an arbitrary string to a string that is a valid variable name in python.
Here's a very basic example:
s1 = 'name/with/slashes'
s2 = 'name '
def clean(s):
s = s.replace('/','')
s = s.strip()
return s
print clean(s1)+'_'#the _ is there so I can see the end of the string
That is a very naive approach. I need to check if the string contains invalid variable name characters and replace them with ''
What would be a pythonic way to do this ?
解决方案
According to Python, an identifier is a letter or underscore, followed by an unlimited string of letters, numbers, and underscores:
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
Use like this:
>>> clean(' 32v2 g #Gmw845h$W b53wi ')
'v2gGmw845hWb53wi'
这篇关于如何在python中将字符串转换为有效的变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文