bytes.title() returns a new bytes object in title case: the first ASCII letter of each word is uppercase and the following letters are lowercase.
A "word" is simply a run of ASCII letters. Any other byte, such as a space, hyphen, digit, apostrophe, or a non-ASCII byte, ends the word, so the next letter starts a new one. That makes title() great for HTTP-style header names and surprising for text like it's.
bytes.title() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.title(...). No import is needed, and bytearray objects have the same method.
Syntax
No arguments; the title-cased copy is returned.
python
result = data.title()
Call
What it does
b"content-type".title()
Returns b'Content-Type'.
b"HELLO wORLD".title()
Returns b'Hello World'.
b"3rd".title()
Returns b'3Rd': the digit breaks the word.
The rule is purely mechanical; it knows nothing about real words or names.
Method signatures
python
bytes.title()
# returns a new bytes object (bytearray.title() returns a bytearray)
Parameters
title() takes no parameters.
Return Value
Return Value
Description
bytes
A copy where each run of ASCII letters starts uppercase and continues lowercase.
Python Examples
Example 1 — Format HTTP Header Names
Header names are case-insensitive, but they are conventionally written with a capital after each hyphen. title() does exactly that.
python
for name in [b"content-type", b"x-request-id", b"user agent"]:
print(name.title())
Output
b'Content-Type'
b'X-Request-Id'
b'User Agent'
How It Works
Hyphen breaks words. After each hyphen the next letter is uppercased.
Single letters too. The one-letter word x becomes X.
Spaces work the same. Any non-letter byte, including a space, starts a new word.
Example 2 — Apostrophe and Digit Pitfalls
Title-case a phrase containing an apostrophe and an ordinal number, then check the result with istitle().