I want to know how to capitalize the first letter of a word in a string

Asked 2 years ago, Updated 2 years ago, 40 views

'the brown fox' -> 'The Brown Fox' I want to capitalize the first letter of every word in the string in this way. Please tell me the easiest way

python capitalize

2022-09-21 20:00

1 Answers

Usually, if you want to convert only the first letter to uppercase, use the following three methods:

mystr = "john, they're bill's friends from the UK"
print mystr.capitalize()

Output: John, they're Bill's friends from the uk

str.capitalize() returns str with only the first letter of str in uppercase and all others in lowercase.

mystr = "john, they're bill's friends from the UK"
print mystr.title()

Output: John, They're Bill's Friends From The Uk

str.title() returns str that converts the first letter of all words into uppercase and other lowercase letters. Since the criteria for dividing words include quotation marks and double quotes as well as blank characters, you should be careful if there are quotes in the string.

import string
mystr = "john, they're bill's friends from the UK"
print string.capwords(mystr)

Output: John. They're Bill's Friends From The Uk

string.capwords(s[, step]) is

It is implemented in that way. If sep is not specified, all blank characters will be changed to one space ("") so please write carefully. If sep is specified, sep is used in split() and join()

import string
mystr = "john.\nthey're bill's        friends from the UK"
print "sep = None:\n", string.capwords(mystr)
print "----------------"
print "sep = '\\n':\n", string.capwords(mystr, "\n")

Result:

sep = None:
John. They're Bill's Friends From The Uk
----------------
sep = '\n':
John.
They're bill's        friends from the uk


2022-09-21 20:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.