Python程序将骆驼大小写字符串转换为蛇大小写
给定一个驼峰式大小写的字符串,编写一个Python程序将给定的字符串从驼峰式大小写转换为蛇形大小写。
例子:
Input : GeeksForGeeks
Output : geeks_for_geeks
Input : ThisIsInCamelCase
Output : this_is_in_camel_case
让我们看看我们可以用不同的方式来完成这项任务。
方法#1:朴素的方法
这是将骆驼案转换为蛇案的幼稚实现。首先,我们用一个空列表初始化一个变量“res”,并将第一个字符(小写)附加到它上面。现在,每次遇到大写字母时,我们都会将“_”和字母(小写)附加到“res”,否则,只附加字母。
Python3
# Python3 program to convert string
# from camel case to snake case
def change_case(str):
res = [str[0].lower()]
for c in str[1:]:
if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
res.append('_')
res.append(c.lower())
else:
res.append(c)
return ''.join(res)
# Driver code
str = "GeeksForGeeks"
print(change_case(str))
Python3
# Python3 program to convert string
# from camel case to snake case
def change_case(str):
return ''.join(['_'+i.lower() if i.isupper()
else i for i in str]).lstrip('_')
# Driver code
str = "GeeksForGeeks"
print(change_case(str))
Python3
# Python3 program to convert string
# from camel case to snake case
from functools import reduce
def change_case(str):
return reduce(lambda x, y: x + ('_' if y.isupper() else '') + y, str).lower()
# Driver code
str = "GeeksForGeeks"
print(change_case(str))
Python3
# Python3 program to convert string
# from camel case to snake case
import re
def change_case(str):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', str)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
# Driver code
str = "GeeksForGeeks"
print(change_case(str))
输出:
geeks_for_geeks
方法#2:列表理解
Python3
# Python3 program to convert string
# from camel case to snake case
def change_case(str):
return ''.join(['_'+i.lower() if i.isupper()
else i for i in str]).lstrip('_')
# Driver code
str = "GeeksForGeeks"
print(change_case(str))
输出:
geeks_for_geeks
方法#3: Python reduce()
Python reduce()方法将一个函数应用于所有字符串字母,即无论在哪里找到大写字母,它都会在其前面添加“_”并将大写字母替换为小写字母。
Python3
# Python3 program to convert string
# from camel case to snake case
from functools import reduce
def change_case(str):
return reduce(lambda x, y: x + ('_' if y.isupper() else '') + y, str).lower()
# Driver code
str = "GeeksForGeeks"
print(change_case(str))
输出:
geeks_for_geeks
方法 #4: Python正则表达式
Python3
# Python3 program to convert string
# from camel case to snake case
import re
def change_case(str):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', str)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
# Driver code
str = "GeeksForGeeks"
print(change_case(str))
输出:
geeks_for_geeks