📜  Python - 将 Snake Case 字符串转换为 Camel Case

📅  最后修改于: 2022-05-13 01:55:06.673000             🧑  作者: Mango

Python - 将 Snake Case 字符串转换为 Camel Case

给定一个蛇形大小写字符串,转换为驼色大小写。

方法 #1:使用 split() + join() + title() + 生成器表达式

以上功能的组合可以解决这个问题。在这种情况下,我们首先拆分所有下划线,然后加入附加初始单词的字符串,然后使用生成器表达式和 title() 将标题大小写的单词连接起来。

Python3
# Python3 code to demonstrate working of 
# Convert Snake Case String to Camel Case
# Using split() + join() + title() + generator expression
  
# initializing string
test_str = 'geeksforgeeks_is_best'
  
# printing original string
print("The original string is : " + str(test_str))
  
# split underscore using split
temp = test_str.split('_')
  
# joining result 
res = temp[0] + ''.join(ele.title() for ele in temp[1:])
      
# printing result 
print("The camel case string is : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert Snake Case String to Camel Case
# Using split() + join() + title() + map()
  
# initializing string
test_str = 'geeksforgeeks_is_best'
  
# printing original string
print("The original string is : " + str(test_str))
  
# saving first and rest using split()
init, *temp = test_str.split('_')
  
# using map() to get all words other than 1st
# and titlecasing them
res = ''.join([init.lower(), *map(str.title, temp)])
      
# printing result 
print("The camel case string is : " + str(res))


输出
The original string is : geeksforgeeks_is_best
The camel case string is : geeksforgeeksIsBest

方法 #2:使用 split() + join() + title() + map()

以上功能的组合可以解决这个问题。在这里,我们使用 map() 执行将逻辑扩展到整个字符串的任务。

蟒蛇3

# Python3 code to demonstrate working of 
# Convert Snake Case String to Camel Case
# Using split() + join() + title() + map()
  
# initializing string
test_str = 'geeksforgeeks_is_best'
  
# printing original string
print("The original string is : " + str(test_str))
  
# saving first and rest using split()
init, *temp = test_str.split('_')
  
# using map() to get all words other than 1st
# and titlecasing them
res = ''.join([init.lower(), *map(str.title, temp)])
      
# printing result 
print("The camel case string is : " + str(res)) 
输出
The original string is : geeksforgeeks_is_best
The camel case string is : geeksforgeeksIsBest