Python string functions are tools for creating, inspecting, searching, and changing text. Most text operations are methods called on a string, such as text.lower() or text.split(); built-in functions such as len(text) and str(value) work with strings too.
What Python Means by a String Function
A Python string is an immutable sequence of Unicode characters, represented by the str type. “String function” is a convenient general phrase, but it covers two different forms of operation. A method belongs to an object and is called after a dot: 'Hello'.upper(). A built-in function is called by name and receives its input in parentheses: len('Hello').
Because strings are immutable, a method that appears to change text actually returns a new string. The original stays the same unless your code assigns the result back to a variable:
name = 'Maya'followed byname.upper()produces'MAYA', but leavesnameas'Maya'.name = name.upper()reassigns the variable to the new string.
This distinction matters when cleaning input or building output: calling a method without using its return value usually has no lasting effect. Strings can also be indexed and sliced, like other sequences. For example, 'Python'[0] is 'P', and 'Python'[1:4] is 'yth'.
Everyday Case and Whitespace Methods
Case methods are useful for presentation and comparisons. lower() converts letters to lowercase, and upper() converts them to uppercase. capitalize() uppercases the first character and lowercases the rest; title() applies title-style capitalization to words. These operations do not know the intended style of a person’s name or a sentence, so their output may not match every writing convention.
For case-insensitive comparisons, casefold() is designed to be more thorough than lower(), particularly for Unicode text. For example, a program comparing words without regard to case can compare their case-folded forms. This still does not perform every kind of language-aware matching, and it does not remove accents.
Use strip() to remove whitespace from both ends of a string, or lstrip() and rstrip() to trim only the left or right end. By default, they remove whitespace such as spaces and line breaks. They do not remove whitespace from the middle:
' hello\n'.strip()returns'hello'.' one two '.strip()returns'one two'.
If you pass characters to strip(chars), Python treats them as a set of characters to remove repeatedly from the ends, not as one exact prefix or suffix. For instance, 'www.example.com'.strip('w.com') can remove several matching end characters; it is not a reliable way to remove a specific domain prefix. Use removeprefix() or removesuffix() when you mean an exact prefix or suffix.
Searching, Checking, and Replacing Text
Use in to test whether one string occurs inside another: 'py' in 'python' is True. The methods find() and rfind() return the position of the first or last match, or -1 if there is no match. Their counterparts, index() and rindex(), raise ValueError when the requested text is absent. Choose based on whether a missing match is an ordinary result or an error in your program.
startswith() and endswith() test the beginning and end of a string. They can accept a tuple of possible prefixes or suffixes, which is handy for checking file-name endings. These checks are case-sensitive unless you normalize the text first.
replace(old, new) returns a copy with matching occurrences changed. An optional third argument limits the number of replacements. It replaces literal text, not patterns: 'cat 42'.replace('cat', 'dog') changes the word, but replace() does not interpret a pattern such as “any digit.” For pattern matching, Python’s re module provides regular expressions; use it when the search rule genuinely needs patterns rather than a fixed substring.
String predicates answer questions about the characters in a string. Examples include isalpha() for alphabetic characters, isdigit() for digit characters, isalnum() for alphanumeric characters, and isspace() for whitespace. An empty string generally does not pass these tests. These methods are not substitutes for validating a full business rule: for example, isalpha() does not establish that text is a valid name in a particular system.
Splitting and Joining Strings
split() breaks text into a list. With no separator, it splits on runs of whitespace and omits empty pieces at the edges. With a separator, it splits at that exact string, and consecutive separators can produce empty items. An optional maxsplit limits how many splits are made. For example, splitting a comma-separated line can preserve an empty field between two commas, which may be important when interpreting data.
rsplit() works from the right, which is useful when only the final portion should be separated. splitlines() divides text at line boundaries. To split on a fixed delimiter and keep the two sides together with the delimiter represented separately, use partition(); it returns a three-item tuple containing the part before, the separator, and the part after. rpartition() does the same from the right.
The inverse of splitting is often join(). It is called on the separator and takes an iterable of strings:
', '.join(['red', 'green', 'blue'])returns'red, green, blue'.''.join(['Py', 'thon'])returns'Python'.
Every item passed to join() must be a string; convert numbers explicitly if needed. For assembling many pieces, collecting them and joining once is clear and commonly efficient. A frequent mistake is to call parts.join(', '); the separator goes before the dot, as in ', '.join(parts).
Formatting Values into Text
Formatted string literals, usually called f-strings, are a readable way to insert expressions into text. Prefix a quoted string with f and put an expression in braces: name = 'Ari' followed by f'Hello, {name}!' produces 'Hello, Ari!'. Format specifications after a colon control details such as decimal places, alignment, and padding. For example, f'{3.14159:.2f}' displays the number with two digits after the decimal point.
The older str.format() method remains useful, especially in reusable templates: '{} scored {:.1f}%'.format('Mina', 93.5) produces 'Mina scored 93.5%'. For simple conversion, str(value) returns a human-readable string representation; repr(value) aims to provide an unambiguous representation useful for debugging. Neither should be mistaken for a secure serialization format.
Formatting is not the same as escaping. Inserting untrusted input into an f-string does not make it safe for HTML, shell commands, or SQL. Use the escaping or parameterization facilities designed for the destination. For database queries, for example, pass values using the database library’s parameterized-query interface rather than building SQL by concatenating strings.
Built-In Functions and Character Codes
Several built-ins work naturally with strings. len(text) returns the number of Unicode code points in the string. str(value) converts many values to text, and sorted(text) returns a list of its characters in sorted order. The ord(character) function returns the Unicode code point for a single character, while chr(number) returns the character for a valid code point. These are not byte positions or display-width measurements.
That distinction explains why len() can surprise users. A visible symbol may consist of multiple code points, such as a letter plus a combining accent, and some emoji are formed from several code points. Python counts code points, not user-perceived grapheme clusters. If an application needs to count what people perceive as displayed characters, it may need Unicode-aware grapheme segmentation rather than a simple len().
Unicode, Encodings, and Text Boundaries
Python str values represent Unicode text; files, network protocols, and many external systems transmit bytes. Convert between them explicitly with encode() and decode(). For example, 'café'.encode('utf-8') produces bytes, while those bytes can be decoded with the same encoding. Choosing the wrong encoding or decoding arbitrary bytes as text can raise UnicodeDecodeError or produce incorrect results if an error-handling option is used.
Unicode allows some visually similar text to be represented in different ways. A precomposed accented character and a base letter followed by a combining mark can look alike but compare as different sequences. The standard library’s unicodedata.normalize() can normalize text to a chosen Unicode normalization form when a system needs consistent comparisons or storage. Normalization is a separate concern from lowercasing and should be applied only when appropriate to the data and requirements.
Also remember that string positions refer to code points, not encoded bytes. A character outside the ASCII range can take multiple bytes in UTF-8 while still being one code point in a Python string. This is why slicing a decoded string and slicing its encoded bytes are different operations.
Choosing the Right Operation and Avoiding Mistakes
For fixed text, use straightforward methods rather than a complex expression. For regular expressions, choose re only when a pattern is needed. For formatted output, use f-strings for clarity or format() where a template is more suitable. For assembling a list of pieces, use join(); for a simple one-off combination, + is often easiest to read.
Common errors include expecting a method to alter a string in place, using find() without checking its -1 result, and assuming that strip('xyz') removes the exact substring 'xyz'. Another trap is calling split(''): an empty separator is not allowed and raises ValueError. If the goal is to get individual code points, iterate over the string or use list(text); if the goal is words, split on whitespace or use a more specific parser suited to the input format.
Repeated concatenation in a loop can create avoidable work when constructing long output. A list of fragments followed by ''.join(fragments) makes the intended operation explicit. For small, clear expressions, however, there is no need to replace readable code with a more elaborate pattern solely for performance. Measure a real bottleneck before optimizing.
Frequently Asked Questions
What is the difference between a Python string function and a method?
A method is called on a string, as in text.upper(). A built-in function receives a string as an argument, as in len(text). People often use “string function” informally to mean either kind of operation.
How do I make a string lowercase in Python?
Call lower() and use its returned value, such as clean = text.lower(). Use casefold() instead when you specifically need more thorough Unicode-aware case-insensitive matching.
How can I remove spaces from a string?
Use strip() to remove whitespace at both ends, or replace(' ', '') if you intend to remove ordinary space characters throughout. The latter does not remove every kind of whitespace, so choose based on the input you need to handle.
How do I check whether a string contains a word?
Use the in operator, for example 'error' in message. It is case-sensitive and checks for a literal substring, not a whole word; use boundaries or a regular expression if whole-word matching is required.
Do Python string methods change the original string?
No. Strings are immutable, so methods such as replace() and strip() return new strings. Assign the result if you want to keep it, for example text = text.strip().
Related
- Snowflake SPLIT_PART: Syntax, Examples & Tips
- Snowflake SPLIT_PART: Syntax, Examples, and Common Issues
- JavaScript split() Explained: Strings, Limits, and Examples
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Sort an Excel Column Alphabetically Without Mixing RowsTo sort a column alphabetically in Excel for Microsoft 365 on Windows, click a cell in the column…
- Calculate ROI in Excel: Formula, Examples, and TipsTo calculate ROI in Excel, subtract the investment cost from the value it generated, then divide the result…
- Excel Sum Unique Values: Formula Rules and ExamplesTo add each different numeric value once in Excel, put the values in B2:B8 and enter =SUM(UNIQUE(B2:B8)). The…
- Excel Formula to List Only Weekdays in a Date RangeWith actual Excel dates in A2:A100, use =FILTER(A2:A100,IFERROR(WEEKDAY(A2:A100,2)<=5,FALSE),"No weekdays") to return only Monday-to-Friday dates from that list. If…
- Rows in Excel Nederlands: Meaning and the RIJEN FunctionIn Dutch, Excel rows are called rijen; the English Excel function ROWS is named RIJEN in Dutch-language Excel.…
- Excel Sum Highlighted Cells: Quick Methods and FormulasTo add numbers in cells you have selected, select them and read Sum on Excel’s status bar; to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.