VMware ESXi and vSphere Cluster Management
Python String Functions and Methods
Learn how to measure, normalize, inspect, and change the case of Python strings with len(), strip(), lower(), upper(), capitalize(), swapcase(), isdigit(), and islower().
A string is an ordered sequence of text characters in Python. String literals are written inside single or double quotes.
greeting = "Hello, Python!"
name = 'Ada'
print(greeting)
Strings can contain letters, digits, spaces, punctuation, and other characters. Python strings are immutable: their contents cannot be changed in place. Most string operations return a new value, so you must save that returned value if you want to keep it.
String methods versus built-in functions
A string method is an operation available on a string value. Methods use dot notation:
text.lower()
text.upper()
text.strip()
The parentheses call the method. A method call produces a return value, which can be printed, assigned, compared, or passed to another operation.
A built-in function is provided by Python and can be used without importing a module. Built-in functions receive values as arguments:
len(text)
Here, len is a built-in function, not a string method. Therefore, use len(text), not text.len().
Most methods in this lesson do not modify the original string variable. They return another string or a Boolean value.
Common Python string functions and methods
| Operation | Call form | Purpose | Example input | Result | Return type |
|---|---|---|---|---|---|
capitalize() | text.capitalize() | Uppercase the first character and lowercase other cased characters | "hELLO" | "Hello" | String |
isdigit() | text.isdigit() | Test whether the non-empty string contains only digit characters | "2048" | True | Boolean |
islower() | text.islower() | Test whether cased characters are lowercase and at least one cased character exists | "hello!" | True | Boolean |
len() | len(text) | Count characters | "Hi!" | 3 | Integer |
lower() | text.lower() | Convert uppercase alphabetic characters to lowercase | "PyTHon" | "python" | String |
upper() | text.upper() | Convert lowercase alphabetic characters to uppercase | "PyTHon" | "PYTHON" | String |
strip() | text.strip() | Remove whitespace from both ends | " hi " | "hi" | String |
swapcase() | text.swapcase() | Reverse the case of alphabetic characters | "PyTHon" | "pYthON" | String |
Measuring strings with len()
Use the built-in len() function to count the characters in a string. Spaces and punctuation count too.
message = "Hi, Ada!"
print(len(message)) # 8
The string contains two letters in Hi, a comma, a space, three letters in Ada, and an exclamation mark.
You can use the result in a condition, such as a simple length check:
username = "ada"
if len(username) >= 3:
print("Username length is acceptable")
else:
print("Username is too short")
len() counts characters, not necessarily what a user would call visible symbols in every Unicode situation. For beginner programs and ordinary text, this distinction is usually not important.
Changing capitalization
lower()
lower() returns a version with uppercase alphabetic characters converted to lowercase. It is useful for case-insensitive comparisons and normalization.
command = "QUIT"
normalized = command.lower()
print(normalized) # quit
upper()
upper() returns a version with lowercase alphabetic characters converted to uppercase. It is useful for headings, labels, or normalized codes when uppercase is required.
label = "warning"
print(label.upper()) # WARNING
capitalize()
capitalize() returns a string whose first character is uppercase when applicable, while the remaining cased characters are converted to lowercase.
title = "pYTHON PROGRAMMING"
print(title.capitalize()) # Python programming
Use it when you want sentence-like display text. It is not appropriate when every original uppercase letter must be preserved.
swapcase()
swapcase() reverses the case of alphabetic characters: uppercase becomes lowercase and lowercase becomes uppercase.
text = "Hello, PYTHON!"
print(text.swapcase()) # hELLO, python!
Non-alphabetic characters such as spaces, numbers, and punctuation are generally unchanged by these case-conversion methods.
Testing string content
isdigit() and islower() return a Boolean value: either True or False.
isdigit()
isdigit() returns True only when the string is non-empty and every character is recognized as a digit by Python's string classification rules.
value = "2048"
if value.isdigit():
print("This is digit-only text")
else:
print("This contains something other than digits")
It is a test of text, not a numeric conversion. A sign, decimal point, or surrounding whitespace prevents a simple digit-only result:
print("2048".isdigit()) # True
print("-2048".isdigit()) # False
print("20.48".isdigit()) # False
print(" 2048 ".isdigit()) # False
print("".isdigit()) # False
Use strip() first when outer whitespace is allowed. Signed or decimal numbers need validation and parsing appropriate to those formats.
islower()
islower() returns True when at least one cased character exists and all cased characters are lowercase. Digits, spaces, and punctuation do not themselves have case and do not make an otherwise lowercase string fail.
print("hello".islower()) # True
print("hello 123!".islower()) # True
print("Hello".islower()) # False
print("123!".islower()) # False
print("".islower()) # False
Thus, islower() does not mean “contains only lowercase letters.” For letters-only validation, combine appropriate checks or use a more specific validation strategy.
String test method edge cases
| Input category | Example value | isdigit() result | islower() result | Explanation |
|---|---|---|---|---|
| Digits only | "123" | True | False | Digits are valid digit characters, but there is no cased character for islower(). |
| Lowercase letters only | "abc" | False | True | The letters are cased and all lowercase. |
| Mixed case letters | "aBc" | False | False | An uppercase cased character is present. |
| Letters and digits | "abc123" | False | True | The digits prevent isdigit(), but do not prevent lowercase classification. |
| Whitespace around digits | " 123 " | False | False | Whitespace is not a digit, and there are no cased characters. |
| Empty string | "" | False | False | Both tests require the appropriate non-empty content; islower() also requires a cased character. |
| Punctuation only | "!?" | False | False | Punctuation is neither a digit nor a cased character. |
Removing outer whitespace with strip()
Whitespace includes characters such as spaces, tabs, and newline characters. strip() removes whitespace from the beginning and end of a string while preserving whitespace inside it.
raw_name = " Ada Lovelace "
clean_name = raw_name.strip()
print(repr(clean_name)) # 'Ada Lovelace'
print(repr(raw_name)) # ' Ada Lovelace '
repr() creates a representation that makes invisible leading and trailing whitespace easier to see. This is especially useful when debugging input from users or files.
text = " red blue "
print(repr(text.strip())) # 'red blue'
The three internal spaces remain. strip() is not a general internal whitespace replacement operation.
Related methods remove whitespace from only one side:
lstrip()removes whitespace from the left, or beginning.rstrip()removes whitespace from the right, or end.
Combining string operations
Method chaining means calling a method on the value returned by another method. For example, trim user input and then normalize its case before comparing it.
answer = " YES "
if answer.strip().lower() == "yes":
print("The answer is yes")
Evaluation proceeds from left to right: strip() first returns "YES", then lower() returns "yes". The comparison then tests that result.
You can assign the result back to the existing variable or use a new variable:
name = " ADA "
name = name.strip().capitalize()
print(name) # Ada
raw_command = " RUN "
command = raw_command.strip().lower()
print(command) # run
print(raw_command) # ' RUN '
Assigning back to name replaces which string the variable refers to. It does not mutate the original string object.
Practical example: inspect a greeting
greeting = "Hello, Python!"
print(len(greeting)) # 15
print(greeting.isdigit()) # False
print(greeting.islower()) # False
print(greeting.lower()) # hello, python!
print(greeting.swapcase()) # hELLO, pYTHON!
Each call produces a result from the same source string. The calls that transform case do not change greeting automatically.
Practical example: clean a name
entered_name = " gRACE HOPPER "
clean_name = entered_name.strip()
display_name = clean_name.capitalize()
print(repr(entered_name)) # ' gRACE HOPPER '
print(display_name) # Grace hopper
This demonstrates two important details: strip() removes only outer whitespace, and capitalize() lowercases the other cased characters. If preserving capitalization of each word matters, this particular method is not enough; choose a formatting approach that matches the requirement.
Practical example: validate a whole-number text field
entered = input("Enter a whole number: ")
number_text = entered.strip()
if number_text.isdigit():
print("The input contains digits only")
else:
print("Enter a non-empty, unsigned whole number")
This accepts text such as "42" and, after trimming, " 42 ". It rejects an empty value, "-42", and "4.2". If negative or decimal values should be accepted, use validation and numeric conversion designed for those formats rather than relying on isdigit() alone.
Practical example: case-insensitive command comparison
entered_command = input("Command: ")
command = entered_command.strip().lower()
if command == "quit":
print("Exiting")
elif command == "help":
print("Showing help")
else:
print("Unknown command")
Normalizing the input before comparison prevents differences in outer whitespace or letter case from affecting the command. Python comparisons are normally case-sensitive, meaning uppercase and lowercase letters are treated as different unless you normalize them first.
Original strings and returned values
| Operation | Original value before call | Returned value | Original value after call | Key takeaway |
|---|---|---|---|---|
lower() | "Hi" | "hi" | "Hi" | Save the result if lowercase text is needed. |
upper() | "Hi" | "HI" | "Hi" | The original is unchanged. |
strip() | " hi " | "hi" | " hi " | Only the returned string has its outer whitespace removed. |
swapcase() | "Hi" | "hI" | "Hi" | Case reversal creates another string. |
capitalize() | "hELLO" | "Hello" | "hELLO" | The first character is capitalized and other cased characters are normalized. |
Common mistakes and troubleshooting
Using text.len()
Problem: text.len() causes an error.
Cause: len is a built-in function, not a string method.
Fix:
length = len(text)
Forgetting to save a transformed string
Problem: Calling text.lower() appears to have no effect.
Cause: The returned lowercase string was not assigned or used.
Fix:
text = text.lower()
# or
print(text.lower())
Expecting isdigit() to parse numbers
isdigit() only classifies text. It does not turn text into an integer or accept signs, decimal points, or untrimmed spaces. Use strip() when outer whitespace is allowed, then use suitable parsing and error handling for more complex numeric formats.
Interpreting islower() as letters-only validation
"abc123".islower() is True because the cased letters are lowercase and the digits have no case. Use additional checks if the input must contain letters only.
Expecting strip() to remove internal spaces
strip() removes matching whitespace only at the two ends. It preserves spaces between words. Use another transformation when internal whitespace needs to be changed.
Misreading capitalize()
capitalize() intentionally lowercases the cased characters after the first one. For example, "pYTHON".capitalize() returns "Python". Choose it only when that normalization is wanted.
Exam-relevant notes
len(text)is a built-in function call; methods use forms such astext.lower().len()counts spaces and punctuation.- String methods generally return new strings because strings are immutable.
isdigit()returnsFalsefor an empty string, signs, decimal points, and whitespace.islower()requires at least one cased character, but digits and punctuation do not prevent a lowercase result.strip()removes outer whitespace, not internal whitespace.- In
text.strip().lower(), stripping occurs before lowercasing.
For related string topics, continue with Python string functions and methods.