Geo*_*nza 18 python string variables validation
我需要将任意字符串转换为python中有效变量名称的字符串.
这是一个非常基本的例子:
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
Run Code Online (Sandbox Code Playgroud)
这是一种非常天真的方法.我需要检查字符串是否包含无效的变量名字符并将其替换为''
什么是pythonic方式来做到这一点?
Nas*_*nov 40
好吧,我想最好的Triptych解决方案......一个单行!
>>> clean = lambda varStr: re.sub('\W|^(?=\d)','_', varStr)
>>> clean('32v2 g #Gmw845h$W b53wi ')
'_32v2_g__Gmw845h_W_b53wi_'
Run Code Online (Sandbox Code Playgroud)
此替换用下划线替换任何非变量的适当字符,如果字符串以数字开头,则在前面插入下划线.IMO,"名/与/斜杠"看起来变量名更好的name_with_slashes不是namewithslashes.
Tri*_*ych 28
根据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
Run Code Online (Sandbox Code Playgroud)
使用这样:
>>> clean(' 32v2 g #Gmw845h$W b53wi ')
'v2gGmw845hWb53wi'
Run Code Online (Sandbox Code Playgroud)
您可以将内置 func:str.isidentifier()与 结合使用filter()。这不需要导入,例如re和 通过迭代每个字符并返回它(如果它是标识符)来工作。然后你只需执行 a''.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
Run Code Online (Sandbox Code Playgroud)
编辑:
如果像回复中的 Hans Bouwmeester 一样,也希望包含数值,您可以创建一个 lambda,它使用 isIdentifier 和 isdecimal 函数来检查字符。显然,这可以根据您的需要进行扩展。代码:
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) }_')
Run Code Online (Sandbox Code Playgroud)
给出:
namewithslashes_
namei2i3_
epng202gq4o22t1l32vqvr0342_
Run Code Online (Sandbox Code Playgroud)