Python string case
last modified November 19, 2026 Python 3.15
In this article we show how to change the case of strings in Python.
Python strings have five methods that change the case of letters:
upperconverts all letters to uppercase,lowerconverts all letters to lowercase,capitalizeuppercases the first character and lowercases the rest,titleuppercases the first letter of each word,swapcaseswaps uppercase and lowercase letters.
Like all string methods, they return a new string. For comparing strings
without regard to case we use casefold, which is covered in
Python compare strings.
Upper and lower case
The upper and lower methods convert all letters of a
string.
#!/usr/bin/python word = 'Falcon' print(word.upper()) print(word.lower()) print(word) code = 'sk-ba-42x' print(code.upper())
The third line shows that the original string is unchanged. Characters that are not letters, such as digits and hyphens, pass through untouched.
$ python case_basic.py FALCON falcon Falcon SK-BA-42X
capitalize and title
The capitalize method changes the first character of the
string; title changes the first letter of every word.
#!/usr/bin/python text = 'an old falcon flew over the hills' print(text.capitalize()) print(text.title()) name = 'mcDONALD' print(name.capitalize()) print(name.title())
Both methods also lowercase all other letters. That is why
mcDONALD becomes Mcdonald rather than
McDonald: names with internal capitals cannot be restored by a
simple rule.
$ python title_capitalize.py An old falcon flew over the hills An Old Falcon Flew Over The Hills Mcdonald Mcdonald
Pitfalls of title
The title method starts a new word after every character that is
not a letter, including apostrophes and digits.
#!/usr/bin/python
import re
import string
text = "they're bill's friends from the u.s.a. 2nd team"
print(text.title())
print(string.capwords(text))
def title_words(s):
return re.sub(r"\b[A-Za-z]+('[A-Za-z]+)?",
lambda m: m.group().capitalize(), s)
print(title_words(text))
The title method produces They'Re and
2Nd. The string.capwords function splits the text on
whitespace and capitalizes each word, which fixes the apostrophes but
lowercases the abbreviation. Our title_words function uses a
regular expression: a word starts at a word boundary \b, so the
letters after 2 are not a word, and the optional group keeps an
apostrophe and the following letters in the same word.
$ python title_pitfalls.py They'Re Bill'S Friends From The U.S.A. 2Nd Team They're Bill's Friends From The U.s.a. 2nd Team They're Bill's Friends From The U.S.A. 2nd Team
Swapping case
The swapcase method turns uppercase letters into lowercase ones
and the other way round.
#!/usr/bin/python text = 'Hello World' print(text.swapcase()) print(text.swapcase().swapcase() == text) word = 'Straße' print(word.swapcase()) print(word.swapcase().swapcase())
For ASCII text, swapping twice gives back the original string. This does not
hold in general: the German ß has no single uppercase letter and
becomes SS, and swapping back gives ss.
$ python swapcase.py hELLO wORLD True sTRASSE Strasse
Checking the case
The isupper, islower, and istitle
methods test the case of a string.
#!/usr/bin/python
samples = ['FALCON', 'falcon', 'Falcon Sky', 'Falcon sky',
'ID42', '42', '']
for s in samples:
print(f'{s!r:14} upper={s.isupper()!s:5} lower={s.islower()!s:5} '
f'title={s.istitle()}')
The methods look only at cased characters, so ID42 is uppercase.
A string must contain at least one cased character; for 42 and
the empty string all three methods return False. The
istitle method requires every word to start with an uppercase
letter followed by lowercase ones.
$ python check_case.py 'FALCON' upper=True lower=False title=False 'falcon' upper=False lower=True title=False 'Falcon Sky' upper=False lower=False title=True 'Falcon sky' upper=False lower=False title=False 'ID42' upper=True lower=False title=False '42' upper=False lower=False title=False '' upper=False lower=False title=False
Case beyond ASCII
Case mapping follows the Unicode rules. For some letters, the result has a different length or depends on the position in the word.
#!/usr/bin/python
word = 'Straße'
print(word.upper(), len(word), len(word.upper()))
print('ΟΔΟΣ'.lower())
print('ΣΟΦΙΑ ΚΑΙ ΟΔΟΣ'.lower())
dotted = 'İstanbul'.lower()
print(dotted, len('İstanbul'), len(dotted))
print([hex(ord(c)) for c in dotted[:2]])
print('ı'.upper(), 'i'.upper())
Straße grows from six to seven characters in uppercase. In
Greek, a lowercase sigma at the end of a word is written ς, and
lower applies this rule. The Turkish capital İ
(dotted I) becomes a plain i followed by a combining dot above,
U+0307. Python's case methods do not depend on the locale, so the Turkish
dotless ı and the ordinary i both become
I; correct Turkish case mapping needs a library such as PyICU.
$ python unicode_case.py STRASSE 6 7 οδος σοφια και οδος i̇stanbul 8 9 ['0x69', '0x307'] I I
Uppercasing the first letter
To uppercase only the first letter and keep the rest, we combine slicing with
upper.
#!/usr/bin/python
names = ['iPhone', 'eBay', 'macOS', 'falcon']
def upper_first(s):
return s[:1].upper() + s[1:]
for name in names:
print(f'{name:8} {name.capitalize():8} {upper_first(name)}')
print(repr(upper_first('')))
The capitalize method spoils brand names such as
iPhone. The upper_first function changes only the
first character. The slice s[:1] is used instead of
s[0], so the function also works for an empty string.
$ python first_letter.py iPhone Iphone IPhone eBay Ebay EBay macOS Macos MacOS falcon Falcon Falcon ''
snake_case to camelCase
Python uses snake_case for variable names, while JavaScript and JSON APIs often use camelCase. Converting from snake_case is a matter of splitting and joining.
#!/usr/bin/python
def to_camel(name):
first, *rest = name.split('_')
return first.lower() + ''.join(w.capitalize() for w in rest)
def to_pascal(name):
return ''.join(w.capitalize() for w in name.split('_'))
for name in ['user_id', 'created_at', 'max_retry_count', 'name']:
print(f'{name:16} {to_camel(name):14} {to_pascal(name)}')
The to_camel function keeps the first word in lowercase and
capitalizes the others. In PascalCase, used for class names, every
word is capitalized.
$ python snake_to_camel.py user_id userId UserId created_at createdAt CreatedAt max_retry_count maxRetryCount MaxRetryCount name name Name
camelCase to snake_case
The opposite direction has no separator to split on. We insert underscores
before uppercase letters with re.sub.
#!/usr/bin/python
import re
def naive(name):
return re.sub(r'([A-Z])', r'_\1', name).lower()
def to_snake(name):
name = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', name)
name = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', name)
return name.lower()
names = ['userId', 'CreatedAt', 'HTTPResponseCode', 'parseXML',
'version2Beta', 'id']
for name in names:
print(f'{name:18} {naive(name):22} {to_snake(name)}')
The naive version puts an underscore before every capital, which breaks
PascalCase names and acronyms. The to_snake function uses two
substitutions. The first splits a run of capitals before a capital followed by
a lowercase letter, so HTTPResponse becomes
HTTP_Response. The second inserts an underscore between a
lowercase letter or digit and a capital.
$ python camel_to_snake.py userId user_id user_id CreatedAt _created_at created_at HTTPResponseCode _h_t_t_p_response_code http_response_code parseXML parse_x_m_l parse_xml version2Beta version2_beta version2_beta id id id
Words in any style
A more general approach first splits a name into words, whatever its style, and then joins the words in the target style.
#!/usr/bin/python
import re
WORD = re.compile(r'[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+')
def words(name):
return [w.lower() for w in WORD.findall(name)]
def convert(name):
ws = words(name)
return {
'snake': '_'.join(ws),
'kebab': '-'.join(ws),
'camel': ws[0] + ''.join(w.capitalize() for w in ws[1:]),
'pascal': ''.join(w.capitalize() for w in ws),
'constant': '_'.join(ws).upper(),
}
for name in ['max_retry_count', 'background-color', 'HTTPServerError',
'Page Title 2']:
print(name)
for style, value in convert(name).items():
print(f' {style:9} {value}')
The regular expression has three alternatives: a run of capitals not followed
by a lowercase letter (an acronym), a word with an optional capital, and a
number. Underscores, hyphens, and spaces match none of them and are skipped.
The convert function builds five styles from the same list of
words. The acronym is lost on the way: HTTP becomes
Http in PascalCase.
$ python case_styles.py max_retry_count snake max_retry_count kebab max-retry-count camel maxRetryCount pascal MaxRetryCount constant MAX_RETRY_COUNT background-color snake background_color kebab background-color camel backgroundColor pascal BackgroundColor constant BACKGROUND_COLOR HTTPServerError snake http_server_error kebab http-server-error camel httpServerError pascal HttpServerError constant HTTP_SERVER_ERROR Page Title 2 snake page_title_2 kebab page-title-2 camel pageTitle2 pascal PageTitle2 constant PAGE_TITLE_2
Converting JSON keys
In the last example we convert the camelCase keys of a JSON response to snake_case, so that the data fits Python naming conventions.
#!/usr/bin/python
import json
import re
WORD = re.compile(r'[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+')
def snake(name):
return '_'.join(w.lower() for w in WORD.findall(name))
def convert_keys(data):
if isinstance(data, dict):
return {snake(k): convert_keys(v) for k, v in data.items()}
if isinstance(data, list):
return [convert_keys(item) for item in data]
return data
response = '''{"userId": 42, "displayName": "Jane",
"lastLoginAt": "2026-11-19T08:15:00",
"addresses": [{"streetName": "Main St", "zipCode": "10001"}],
"HTTPStatus": 200}'''
record = convert_keys(json.loads(response))
print(json.dumps(record, indent=2))
The convert_keys function walks the decoded data recursively. It
rebuilds dictionaries with converted keys and lists with converted items;
other values are returned as they are. The string values, such as
Main St, are not changed.
$ python api_keys.py
{
"user_id": 42,
"display_name": "Jane",
"last_login_at": "2026-11-19T08:15:00",
"addresses": [
{
"street_name": "Main St",
"zip_code": "10001"
}
],
"http_status": 200
}
Source
str.upper – Python documentation
string.capwords – Python documentation
In this article we have changed the case of strings in Python and converted identifiers between naming styles. See also Python compare strings, Python string slicing, Python re.sub, and Python string.
Author
List all Python tutorials.