Python string methods are built-in functions you call on a string object to inspect, transform, or split text without importing anything. The shortest working set is: create a string, call a method such as .upper() or .split(), and print the result. Everything below builds on that pattern.
What You'll Need
- Python 3 installed on your computer (any recent 3.x version works; the examples use syntax available in all current 3.x releases).
- A way to run Python: the interactive interpreter, a
.pyfile, or an editor such as IDLE or VS Code. - A basic understanding of variables and printing output.
Step-by-Step
- Open a Python session. Launch the interactive interpreter by typing
python(orpython3on macOS and Linux) in a terminal, or create a new file namedstrings.pyin your editor. Menu labels and terminal commands can differ slightly by operating system and Python version. - Create a string variable. Type
text = " Hello, World! "and press Enter. The leading and trailing spaces are intentional so you can see how trimming methods behave later. - Call a case method. Enter
print(text.upper())to getHELLO, WORLD!. Then tryprint(text.lower())andprint(text.title()). Each returns a new string; the originaltextis unchanged. - Remove whitespace with
.strip(). Runprint(text.strip()). The output isHello, World!without the outer spaces. Use.lstrip()or.rstrip()if you only want to trim one side. - Replace text with
.replace(). Tryprint(text.replace("World", "Python")). The result isHello, Python!. The method takes the old substring first and the new substring second. - Split a string into a list. Run
print(text.strip().split(",")). You get['Hello', ' World!']. Calling.split()with no argument splits on any whitespace instead. - Join a list back into a string. Create a list with
words = ["apple", "banana", "cherry"], then runprint(", ".join(words)). The output isapple, banana, cherry. The separator string comes before.join(). - Check content with
.startswith()and.endswith(). Enterprint(text.strip().startswith("Hello"))to getTrue. These return booleans, so they are useful inifstatements. - Find a substring with
.find(). Runprint(text.find("World")). It returns the index where the substring begins, or-1if it is not found. Use.index()if you prefer an error when the substring is missing. - Chain methods carefully. Methods return new strings, so you can chain them:
print(text.strip().lower().replace("world", "python")). Read left to right; each method acts on the result of the previous one. - Confirm the original string is unchanged. Print
textagain. Strings are immutable in Python, so every method returns a new value rather than editing the variable in place. Assign the result back if you want to keep it:text = text.strip().
Common Mistakes
- Expecting in-place changes. Writing
text.upper()on its own line does nothing visible. You must print it or assign it:text = text.upper(). - Forgetting that
.join()is called on the separator.words.join(", ")raises an error. The correct form is", ".join(words). - Confusing
.find()with.index()..find()returns-1when nothing matches;.index()raises aValueError. Pick the one that matches how you handle missing values. - Assuming
.split()with no argument splits on commas. It splits on runs of whitespace. Pass an explicit separator for anything else. - Mixing up
.strip()arguments..strip("ab")removes any leading or trailing characters that areaorb, not the literal substring"ab".
Tips
- Use
dir(str)in the interpreter to list every string method available in your Python version. - Use
help(str.strip)to read the built-in documentation for any method without leaving the terminal. - Prefer
.casefold()over.lower()when comparing text that may contain accented or non-English characters. - Chain
.strip()before.split()when parsing user input so stray spaces do not create empty entries. - Remember that string methods never modify the original value, which makes them safe to use inside expressions and function calls.
Troubleshooting
AttributeError: 'str' object has no attribute ...Check the spelling and capitalization of the method name. Method names are lowercase and use underscores, not spaces.TypeError: join() argument must be str ...You are passing a non-string separator or a list containing non-strings. Convert items withstr(item)first.- Output still has spaces after
.strip()The spaces may be inside the string, not at the edges. Use.replace(" ", "")or.split()and rejoin. - Method seems to do nothing Confirm you assigned or printed the return value. In the interactive interpreter, just typing the expression shows the result; in a script, you need
print(). - Unexpected result from
.replace().replace()changes every occurrence by default. Pass a third argument to limit the count, for example.replace("a", "b", 1).
Frequently Asked Questions
Do string methods change the original string?
No. Python strings are immutable, so every method returns a new string. Assign the result to a variable if you want to keep it.
What is the difference between .find() and .index()?
.find() returns -1 when the substring is absent. .index() raises a ValueError instead.
How do I split a string on multiple characters?
.split() takes one separator. For several separators, use the re module's re.split() function.
Why does .strip() remove more than I expected?
With no argument it removes whitespace. With an argument it treats that argument as a set of characters, not a whole substring.
Can I chain string methods?
Yes, because each method returns a string. Chain them left to right and check the intermediate result if the output looks wrong.
How do I see all available string methods?
Run dir(str) in the interpreter. For details on one method, run help(str.methodname).