Python:将类似变量的字符串转换为类似类的字符串
我在尝试创建一个可以完成此任务的函数时遇到困难。目标是转换字符串,如Python:将类似变量的字符串转换为类似类的字符串,python,regex,string,Python,Regex,String,我在尝试创建一个可以完成此任务的函数时遇到困难。目标是转换字符串,如 one至one hello\u worldtoHelloWorld foo_bar_baztoFooBarBaz 我知道正确的方法是使用re.sub,但是我很难创建正确的正则表达式来完成这项工作。您可以尝试以下方法: >>> s = 'one' >>> filter(str.isalnum, s.title()) 'One' >>> >>> s = '
至one
one
tohello\u world
HelloWorld
tofoo_bar_baz
FooBarBaz
我知道正确的方法是使用
re.sub
,但是我很难创建正确的正则表达式来完成这项工作。您可以尝试以下方法:
>>> s = 'one'
>>> filter(str.isalnum, s.title())
'One'
>>>
>>> s = 'hello_world'
>>> filter(str.isalnum, s.title())
'HelloWorld'
>>>
>>> s = 'foo_bar_baz'
>>> filter(str.isalnum, s.title())
'FooBarBaz'
相关文档:
>>> s = 'one'
>>> filter(str.isalnum, s.title())
'One'
>>>
>>> s = 'hello_world'
>>> filter(str.isalnum, s.title())
'HelloWorld'
>>>
>>> s = 'foo_bar_baz'
>>> filter(str.isalnum, s.title())
'FooBarBaz'
相关文档:
def uppercase(name):
return ''.join(x for x in name.title() if not x.isspace()).replace('_', '')
找到的解决方案:
def uppercase(name):
return ''.join(x for x in name.title() if not x.isspace()).replace('_', '')
谢谢,这看起来不错!谢谢,这看起来不错!第一个解决方案很漂亮,谢谢!第一个解决方案很漂亮,谢谢!