Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将类似变量的字符串转换为类似类的字符串_Python_Regex_String - Fatal编程技术网

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
  • hello\u world
    to
    HelloWorld
  • foo_bar_baz
    to
    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('_', '')

谢谢,这看起来不错!谢谢,这看起来不错!第一个解决方案很漂亮,谢谢!第一个解决方案很漂亮,谢谢!