我遇到了下面提到的场景:
输入:- parselTongue
预期输出:- parsel_tongue
我的代码:-
empty_string = ""
word = input()
if word.islower() == 1:
empty_string = empty_string + word
print(empty_string)
else:
for char in word:
char = str(char)
if char.isupper() == 1:
x = char
y = word.find(x)
print(char.replace(char, word[0:y] + "_" + char.lower() + word[y:]))我的输出:-
parsel_tTongue
当我的输出是"parsel_tTongue“而不是"parsel_tongue”时,请告诉我哪里出错了。
发布于 2021-06-23 18:57:37
我相信这种方法可以更好。
它防止单词不仅包含字母,而且还包含特殊字符或数字的情况。
word = "camelCaseWord"
res = "" # sanke case word
# handle 1st upper character
if word[0].isupper():
word = word[0].lower() + word[1:]
for w in word:
# Only letter can be upper
if w.isupper():
res += "_" + w.lower()
else:
res += w
print(res)
>>> camel_case_word如果word = "camelCase3Wor& -> >>> camel_case3_wor&
发布于 2021-06-23 18:57:06
更优雅的解决方案是使用理解来实现逻辑。
word = input()
output= ''.join(c if not c.isupper() else f'_{c.lower()}' for c in word)
#output: 'parsel_tongue'发布于 2021-06-23 18:57:14
不需要循环使用正则表达式
import re
name = 'parselTongue'
name = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
print(name) # camel_case_namehttps://stackoverflow.com/questions/68098343
复制相似问题