Reputation: 91999
Is there a library or standard way to perform this task?
Example:
HILO -> Hilo
new york -> New York
SAN FRANCISCO -> San Francisco
Upvotes: 183
Views: 291762
Reputation: 1
Here is an example:
def format_name(f_name,l_name):
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f'{formated_f_name} {formated_l_name}'
print(format_name('GeOrGE', 'MADISON'))
>>> George Madison
Upvotes: -2
Reputation: 171
From code wars - Write simple .camelCase method in Python for strings. All words must have their first letter capitalized without spaces. camelcase("hello case") => HelloCase camelcase("camel case word") => CamelCaseWord
def camel_case(string):
titled_string = string.title()
space_joined_string = titled_string.replace(' ', '')
return space_joined_string
Upvotes: 0
Reputation: 201
def camelCase(st):
s = st.title()
d = "".join(s.split())
d = d.replace(d[0],d[0].lower())
return d
Upvotes: 3
Reputation: 10585
Why not use title
Right from the docs:
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
If you really wanted PascalCase you can use this:
>>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
'MakeItPascalCase'
Upvotes: 377
Reputation: 9246
I would like to add my little contribution to this post:
def to_camelcase(str):
return ' '.join([t.title() for t in str.split()])
Upvotes: 0
Reputation: 958
Potential library: https://pypi.org/project/stringcase/
Example:
import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"
Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)
Upvotes: 9
Reputation: 7100
This one would always start with lowercase, and also strip non alphanumeric characters:
def camelCase(st):
output = ''.join(x for x in st.title() if x.isalnum())
return output[0].lower() + output[1:]
Upvotes: 39
Reputation: 5508
Note: Why am I providing yet another answer? This answer is based on the title of the question and the notion that camelcase is defined as: a series of words that have been concatenated (no spaces!) such that each of the original words start with a capital letter (the rest being lowercase) excepting the first word of the series (which is completely lowercase). Also it is assumed that "all strings" refers to ASCII character set; unicode would not work with this solution).
Given the above definition, this function
import re
word_regex_pattern = re.compile("[^A-Za-z]+")
def camel(chars):
words = word_regex_pattern.split(chars)
return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))
, when called, would result in this manner
camel("San Francisco") # sanFrancisco
camel("SAN-FRANCISCO") # sanFrancisco
camel("san_francisco") # sanFrancisco
Note that it fails when presented with an already camel cased string!
camel("sanFrancisco") # sanfrancisco <-- noted limitation
Note that it fails with many unicode strings
camel("México City") # mXicoCity <-- can't handle unicode
I don't have a solution for these cases(or other ones that could be introduced with some creativity). So, as in all things that have to do with strings, cover your own edge cases and good luck with unicode!
Upvotes: 6
Reputation: 4160
just use .title(), and it will convert first letter of every word in capital, rest in small:
>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True
Upvotes: 8
Reputation: 143204
def capitalizeWords(s):
return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)
re.sub
can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match
object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.
A longer version of the same thing:
WORD_RE = re.compile(r'\w+')
def capitalizeMatch(m):
return m.group(0).capitalize()
def capitalizeWords(s):
return WORD_RE.sub(capitalizeMatch, s)
This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.
Upvotes: 15
Reputation: 9173
Why not write one? Something like this may satisfy your requirements:
def FixCase(st):
return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())
Upvotes: 6