【发布时间】:2011-03-19 05:08:19
【问题描述】:
我需要将任意字符串转换为在 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
这是一种非常幼稚的方法。我需要检查字符串是否包含无效 变量名字符并将其替换为 ''
pythonic 的方法是什么?
【问题讨论】:
-
你想用这个方法解决什么问题?可能有更好的方法。
-
print repr("a string ")在引号中显示字符串 - 比在其上附加_更简洁。 -
我正在遍历来自 Cinema 4d 的场景图,需要在搅拌机中重新创建它。为了让我更容易理解,我想使用cinema4d对象的实际名称作为Blender Python的变量名,所以我需要先调整这些
标签: python validation string variables