In Convert string to camel case:Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
Examples
to_camel_case("the-stealth-warrior") # returns "theStealthWarrior"
to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior"
A smart answer was
def to_camel_case(s):
return s[0] + s.title().translate(None, "-_")[1:] if s else s
But the code raises error in python3, it turns out that translate
in python3 only accepts function str.maketrans
<function str.maketrans(x, y=None, z=None, /)>
The maketrans function accepts:
1.two args, they have to be str of same length
2.one dict
In this problem, we want to delete “-” and “_”, so we need to delever a dict to the str.maketrans
func
def to_camel_case(s):
s = s.strip() # in case ' '
return s[0] + s.title().translate(str.maketrans({'-':None, '_':None}))[1:] if s else s
_boteen_
发布了1 篇原创文章 · 获赞 0 · 访问量 21
私信
关注