将字符串从特殊字符转换为无特殊字符

convert strings from special char to no special char

我正在使用 python 2.7。如果我有一个字符串分配给 name 变量,如下所示

name = "Test with-name and_underscore"

如何将其转换为可分配给 name 变量的字符串

name = "TestWithNameAndUnderscore"

正则表达式是可行的方法还是 python 有任何内置函数可以做到这一点....

所以我正在寻找的是,当一个字符串带有下划线或破折号或 space 或其中的任何特殊字符时,它会转换为相同的东西但没有 underscore/dashes/space/special 字符并且该单词的首字母将以大写字母开头,例如 "test name - is this_here" 到 "TestNameIsThisHere"。

如果没有 space 或没有特殊字符,则不要执行任何操作。因此,如果字符串是 "Helloworld",则跳过它并继续。

我这样做的原因是,我正在使用 python boto 为 AWS 编写一些东西,并且对可以调用的资源有命名限制。它不能是非字母数字

>>> import re
>>> name = "Test with-name and_underscore"
>>> print(''.join(x.capitalize() for x in re.compile(r'[^a-zA-Z0-9]').split(name)))
TestWithNameAndUnderscore

如果需要,您也可以去除前导数字。这是一个稍微更健壮的示例,它将执行此操作并确保生成的字符串不为空:

>>> import re
>>> def fix_id(s, split=re.compile('[^a-zA-Z0-9]+|^[0-9]+').split):
...     result = ''.join(x.capitalize() for x in split(s))
...     if not result:
...         raise ValueError('Invalid ID (empty after edits)')
...     return result
... 
>>> fix_id("Test with-name and_underscore")
'TestWithNameAndUnderscore'
>>> fix_id("123 Test 456 with-name and_underscore 789")
'Test456WithNameAndUnderscore789'
>>> fix_id("Thisshouldbeunmolested")
'Thisshouldbeunmolested'
>>> fix_id('123')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in fix_id
ValueError: Invalid ID (empty after edits)

请注意,这些都不能保证您的标识符的唯一性,例如"Mary-Sue" 和 "mary sue" 将映射到相同的标识符。如果您需要这些映射到不同的标识符,您可以添加一个缓存字典,在其中映射符号并在必要时添加后缀。

这可以在没有 Regex 的情况下使用 Python 中的 isalnum() 函数来完成。

name = "Test with-name and_underscore"
new_name = ''.join(name for name in string if e.isalnum())

当然,如果您坚持使用正则表达式,也可以将 isalnum() 替换为适当的正则表达式函数。

我知道一个愚蠢的方法!

name.replace('_',' ').replace('-',' ')
name = name.title().replace(' ','')

一种可能更小的 re 方法是使用以下内容:

  import re
   string = '123 this is a test_of the-sub method 33'
   varString = re.sub('_?-? ?', '', string)

应该return

>>> sub('_?-? ?','',string) 
'123thisisatestofthesubmethod33'

如果您尝试将其用作变量名,尽管您可能会 运行 遇到一些麻烦,例如太长(符合 pep8 标准)或其他外来字符,例如 !?$% 等。 ..其中上面的 isalpha 方法可能会有所帮助。我会小心地相信字符串的值成为变量名并包装一些约束以避免任何类型的溢出。