How can I capitalize the first letter of each word in a string?
The .title()
method of a string (either ASCII or Unicode is fine) does this:
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
However, look out for strings with embedded apostrophes, as noted in the docs.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
How can I capitalize the first letter of each word in a string using JavaScript?
You are not assigning your changes to the array again, so all your efforts are in vain. Try this:
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
(Python) Capitalize first letter of every word without using .title() or .capitalize()
Break the problem down to its most basic components. First, you will want some way to capitalize a word. You say in your question that you can't use .title() / .capitalize(), etc... so I will assume .upper() is out as well.
So you want a function like this
def capitalize_word(word):
# do something to ensure word starts with a capital letter
# and modify it if it doesn't
return word
And you are going to want a function that takes a sentence, breaks it into words, and capitalizes each of them (ignoring your exclusion words for now)
def titlecase_sentence(sentence):
# break the sentence on spaces
words = sentence.split()
capitalized_words = []
# iterate through your words and store the capitalized version of each
for word in words:
capitalized_word = capitalize_word(word)
capitalized_words.append(capitalized_word)
# join your capitalized words back into a sentence
capitalized_sentence = " ".join(capitalized_words)
return capitalized_sentence
So the two things to figure out are: 1. How does capitalize_word
work, and 2. How do we deal with your exclusion words.
The first one is pretty straight forward if you use the ord
built-in function. ord
returns the ordinal value of an ascii character (its numeric value). The ordinal of 'a'
is 97, the ordinal of 'z'
is 122. Upper case letters come earlier in the numeric values and are 'A'
at 65 and 'Z'
at 90. So you can check whether the ord of the first character of word is between 65 and 90, if it isn't then you know you have a lowercase letter. Converting between a lowercase and capital letter is as easy as subtracting 32 from the ordinal and changing it back into an ascii character via the chr
built-in. Using this you end up with something like
ord_Z = ord('Z')
ord_A = ord('A')
def capitalize_word(word):
first_ord = ord(word[0])
if not (ord_A <= first_ord <= ord_Z):
word = chr(first_ord - 32) + word[1:]
return word
Now we just need to handle your special words that do not get capitalized except when beginning a sentence.
I will leave that part as an exercise, but you essentially want to ALWAYS run the first word the capitalize_word
function, and conditionally run the remaining words through it. If the current word in the iteration is one of your special words then you simply add the word without calling capitalize_word
.
How to capitalize the first character of each word in a string
WordUtils.capitalize(str)
(from apache commons-text)
(Note: if you need "fOO BAr"
to become "Foo Bar"
, then use capitalizeFully(..)
instead)
Python - Capitalize only first letter of each word in a string
This isn't a perfect match for any of the builtin str
methods: .title()
and .capitalize()
will lowercase all letters after the first, while .upper()
will capitalize everything.
It's not elegant, but you can just explicitly capitalize the first letter and append the rest:
def cap(match):
grp = match.group()
return grp[0].upper() + grp[1:]
>>> p.sub(cap, 'CBH1 protein was analyzed. to evaluate the report')
'CBH1 protein was analyzed. To evaluate the report'
How to capitalize the First letter of each word in python?
We can try using re.sub
here matching the pattern \b(.)
, along with a callback function which uppercases the single letter being matched.
inp = '1 w 2 r 3g'
output = re.sub(r'\b(.)', lambda x: x.group(1).upper(), inp)
print(output) # 1 W 2 R 3g
JQ Capitalize first letter of each word
Suppose we are given an array of words that are to be left as is, e.g.:
def exceptions: ["LLC", "USA"];
We can then define a capitalization function as follows:
# Capitalize all the words in the input string other than those specified by exceptions:
def capitalize:
INDEX(exceptions[]; .) as $e
| [splits("\\b") | select(length>0)]
| map(if $e[.] then . else (.[:1]|ascii_upcase) + (.[1:] |ascii_downcase) end)
| join("");
For example, given "abc-DEF ghi USA" as input, the result would be "Abc-Def Ghi USA".
Related Topics
Postgresql Generate Sequence with No Gap
Reference an Alias Elsewhere in the Select List
Which Database Design Gives Better Performance
Inner Join in Update SQL for Db2
How to Add a Auto_Increment Primary Key in SQL Server Database
How to Delete in Ms Access When Using Join'S
Parameterise Table Name in .Net/Sql
I Keep Getting the Error "Relation [Table] Does Not Exist"
Postgres - Where in (List) - Column Does Not Exist
How to Efficiently Delete Rows While Not Using Truncate Table in a 500,000+ Rows Table
The Backend Version Is Not Supported to Design Database Diagrams or Tables
Postgresql: Case Insensitive String Comparison
Foreign Key Creation Issue in Oracle
Connect Different Windows User in SQL Server Management Studio (2005 or Later)