我使用的是python2.7。如果我有一个字符串分配给name变量,如下所示
name = "Test with-name and_underscore"
如何将其转换为可分配给name变量的字符串
name = "TestWithNameAndUnderscore"
正则表达式是一种方法还是python有任何内置函数来实现这一点。。。。你知道吗
所以我要找的是,当一个字符串中有下划线、破折号、空格或任何特殊字符时,它们被转换成相同的东西,但没有下划线/破折号/空格/特殊字符,这个单词的首字母应该以大写字母开头,就像“test name-is this \u here”到“testnameithis here”。你知道吗
如果没有空间或没有特殊的字符,那么不要做任何事情。因此,如果字符串是“Helloworld”,请跳过它并继续。你知道吗
我这样做的原因是,我正在使用python boto为AWS编写一些东西,并且对可以调用的资源有一个命名限制。它不能是非字母数字
如果需要的话,你也可以去掉前导数字。下面是一个更加健壮的示例,它可以做到这一点并确保生成的字符串不是空的:
请注意,这两者都不能保证标识符的唯一性,例如,“Mary Sue”和“Mary Sue”将映射到同一标识符。如果需要将这些映射到不同的标识符,可以添加缓存字典,在其中映射符号,并在必要时添加后缀。你知道吗
我知道一个愚蠢的方法!你知道吗
这可以在不使用Regex的情况下使用Python中的isalnum()函数来完成。你知道吗
当然,如果您坚持使用regex,也可以用适当的regex函数替换isalnum()。你知道吗
相关问题 更多 >
编程相关推荐