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

2024-10-03 04:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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编写一些东西,并且对可以调用的资源有一个命名限制。它不能是非字母数字


Tags: and方法函数字符串nametestherewith
3条回答
>>> 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”将映射到同一标识符。如果需要将这些映射到不同的标识符,可以添加缓存字典,在其中映射符号,并在必要时添加后缀。你知道吗

我知道一个愚蠢的方法!你知道吗

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

这可以在不使用Regex的情况下使用Python中的isalnum()函数来完成。你知道吗

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

当然,如果您坚持使用regex,也可以用适当的regex函数替换isalnum()。你知道吗

相关问题 更多 >