Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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:将snake_case更改为camelCase_Python_String - Fatal编程技术网

Python:将snake_case更改为camelCase

Python:将snake_case更改为camelCase,python,string,Python,String,我如何告诉函数在之后字符应该大写 我想,如果x是,则在其中创建一个计数器,并告诉函数进一步查看,然后将字母转换为大写字母。您可以通过以下方法改进: def to_camel(s:str)->str: con = [] trash = [] for x in s: if x is "_": trash.append(x) elif x in "abcdefghijklmnopqrs

我如何告诉函数在
之后字符应该大写


我想,如果x是
,则在其中创建一个计数器,并告诉函数进一步查看,然后将字母转换为大写字母。

您可以通过以下方法改进:

def to_camel(s:str)->str:
    con = []
    trash = []
    for x in s:
        if x is "_":
            trash.append(x)

        elif x in "abcdefghijklmnopqrstuvwxyz":
          con.append(x)
          
    return "".join(con)


def test_tocamel():

    assert to_camel("my_fancy_function") == "myFancyFunction"
输出:

def to_camel(snake_str: str) -> str:
    first_part, *all_the_rest = snake_str.split('_')
    return ''.join([first_part.lower(), *map(str.title, all_the_rest)])


print(to_camel("my_fancy_fuction"))
assert to_camel("my_fancy_function") == "myFancyFunction"
def到_camel(s):
返回s.replace(“”,“”).title().replace(“”,“”)

上拆分字符串可能更容易,因此您可以执行以下操作:

def to_camel(s:str)->str:
spl=s.split(“uu”)
数据=spl[0]
对于spl[1:]中的w:
数据+=w.大写()
返回数据
紧凑型:

def to_camel(s:str)->str:
返回“.join(w.capitalize(),如果i-else为i,w在枚举(s.split(“”))中)

您创建了一个标志
trash\u,该标志已被看到
。无论何时看到垃圾,都将其设置为
True
。在
elif
的每次迭代中,检查是否看到
trash\u
is
True
。如果是这样的话,
upper()
it并将
trash\u is\u seen
标志设置为
False
给出了
“hello\u world”
,虽然这段代码可能提供了问题的解决方案,但最好添加上下文说明它为什么/如何工作。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。当代码被解释时,你也可能得到用户的积极反馈/支持票。除了像@AmitVerma所说的那样添加上下文外,这个函数实际上是将第一个单词大写,而当人们说他们想要大写时,这通常不是他们想要的。。。
myFancyFuction