On this page

Python Strings: Convert, Clean, Find and Format

Strings are the data type you touch most often in Python: user input, file contents, web pages and CSV rows all arrive as text. They are easy to underestimate, because a Python string is immutable — no method changes it in place; every operation returns a new string. This page organises all 115 DelftStack string guides by the job you are doing, along four task lines: convert text to other types and back, clean away characters that do not belong, find and check what a string contains, and format or replace text for output.

Python string operations at a glance: converting, cleaning, finding and formatting text

The String Learning Path

Start with five minutes of basics: how strings are built, indexed and sliced, and why immutability means you always keep the return value. Next, learn to search and clean — find(), the in operator, strip() and replace() handle most daily text work. Then move to conversion, where strings trade places with lists, numbers, dictionaries and bytes. Finish with formatting and replacement, where f-strings are the default and the older styles appear only where they still earn their place. Each step below is one group on this page, in the order to learn them.

Five-Minute Basics: Build, Join and Repeat

A string is a sequence of characters in single or double quotes; triple quotes span lines, and indexing plus slicing read any part of it. Two facts do most of the work: len() measures a string, and building a longer one always produces a new value.

Convert: Strings to Lists, Numbers and Back

Conversion is where string work earns its keep: data arrives as text and is used as something else. Lists are the busiest doorway, numbers the next; containers flatten with str() or join(), and bytes cross over only through explicit encodings. One neighbour lives elsewhere: turning a datetime into a string belongs to the Datetime guides — see Convert Datetime to String and the Datetime section of the Python pillar.

Clean and Delete: Remove What Does Not Belong

Cleaning is this cluster’s home turf: scraped pages, exports and user input arrive with characters that were never invited. Choose by the shape of the dirt: replace() for one known substring, translate() with a table for a whole set of characters at once, and regex when dirt is a pattern, not a literal.

Find, Check and Count

Finding is the cluster’s biggest unmet demand: readers know the character they want and need its position, its count, or a yes-or-no answer. Keep the division of labour straight — in answers whether, find() answers where first, index() answers where and complains loudly when there is no match, and count() answers how many.

Case, Comparison and Padding

Case is where comparisons quietly go wrong: Python compares by Unicode code point, so case and special letters all count. Normalise before comparing — lower() or upper() for ordinary text, casefold() when Unicode pairs must match — and pad with ljust(), rjust(), center() or zfill() for presentation.

Format and Replace

For new code, formatting means f-strings: values sit inside the template where you can read them, and format specs control width and precision. str.format() remains right when the template lives separately or is reused, and % formatting survives in older code you will still meet. Replacement obeys immutability like everything else — you never edit a string, you build the corrected one.

String Method Map

Python ships 47 built-in string methods, and this map finds the right one fast. Read it by verb: the is* family checks, case methods transform, split and join pull apart and rebuild, search methods locate. Where a guide goes deeper on a method, the third column links to it; an empty cell means the one-line description suffices.

Method What it does Deep dive
capitalize() Capitalise the first character, lowercase the rest Deep dive
casefold() Aggressive lowercase built for caseless matching Deep dive
center() Centre the string in a field of a given width Deep dive
count() Count non-overlapping occurrences of a substring Deep dive
encode() Encode the string to bytes in a chosen encoding Deep dive
endswith() Test whether the string ends with a suffix
expandtabs() Replace tab characters with spaces
find() Lowest index of a substring, or -1 when absent Deep dive
format() Format values into {} placeholders Deep dive
format_map() Like format(), with values taken from a mapping
index() Lowest index of a substring; raises ValueError when absent Deep dive
isalnum() True when every character is a letter or digit Deep dive
isalpha() True when every character is alphabetic
isascii() True when every character is ASCII
isdecimal() True when every character is a decimal digit
isdigit() True when every character is a digit Deep dive
isidentifier() True when the string is a valid Python identifier
islower() True when all cased characters are lowercase
isnumeric() True when every character is numeric
isprintable() True when every character is printable
isspace() True when every character is whitespace
istitle() True when the string is titlecased
isupper() True when all cased characters are uppercase
join() Join an iterable of strings using this string as separator Deep dive
ljust() Left-justify in a field of a given width Deep dive
lower() Return a lowercase copy Deep dive
lstrip() Strip leading characters (whitespace by default)
maketrans() Build a translation table for translate() Deep dive
partition() Split at the first separator into a three-part tuple
removeprefix() Remove a prefix when it is present
removesuffix() Remove a suffix when it is present
replace() Replace occurrences of one substring with another Deep dive
rfind() Highest index of a substring, or -1 when absent Deep dive
rindex() Highest index of a substring; raises ValueError when absent
rjust() Right-justify in a field of a given width Deep dive
rpartition() Split at the last separator into a three-part tuple
rsplit() Split on a separator, counting from the right
rstrip() Strip trailing characters (whitespace by default)
split() Split on a separator into a list Deep dive
splitlines() Split on line boundaries into a list
startswith() Test whether the string starts with a prefix Deep dive
strip() Strip leading and trailing characters Deep dive
swapcase() Return a copy with every character’s case swapped
title() Return a titlecased copy, each word capitalised
translate() Map characters through a translation table Deep dive
upper() Return an uppercase copy Deep dive
zfill() Pad with leading zeros to a given width Deep dive

Frequently Asked Questions

How do I convert a string to a list in Python?

Decide what one item should be, then pick the matching tool. list(text) gives one item per character; text.split() gives words, and text.split(",") gives delimiter-separated fields, preserving empty fields. For text that already looks like a Python list, parse it with ast.literal_eval() and check the result really is a list. Never use eval() on input you do not control. The full walkthrough is How to Convert a String to List in Python.

How do I check whether a string contains a substring or a word?

For a plain substring test, use the in operator: "word" in text returns a Boolean and is case-sensitive. When you also need the position, find() returns the first index or -1, while index() raises ValueError instead. Note that in matches inside larger words — "is" in "This" is true — so for a whole word, tokenise or use a regex with \b boundaries, as shown in How to Check if a String Contains Word in Python.

How do I remove punctuation or special characters from a string?

First define what must go: punctuation only, or everything that is not a letter or digit. For punctuation, filter against string.punctuation, substitute with the regex [^\w\s], or delete a whole set at once with a str.translate() table built by maketrans() — the fastest option. For broader cleaning, an isalnum() filter keeps Unicode letters and digits. How to Strip Punctuation From a String in Python works through each variant.

Why does Python say “not all arguments converted during string formatting”?

This TypeError comes from % formatting: the template holds fewer placeholders than the tuple of values you supplied, so Python reaches the end of the template with arguments left over — for example, "Value: " % (1, 2). Give every value exactly one placeholder, wrap a single value in a one-item tuple, and escape a literal percent sign as %%`. The dedicated error guide dissects the message case by case.

Is there a toString() in Python?

No. Python has no toString() method; looking for one is a habit carried over from Java. The equivalent is the built-in str(value), which returns a readable string for numbers, collections and most objects. Use join() to combine many strings, f-strings to build messages, and define __str__() on your own classes to control how they print. Note that str() produces display text, not JSON or CSV. See tostring() Equivalent in Python.

How do I replace one character at a specific index?

You cannot assign into a string — text[2] = "m" raises TypeError, because strings are immutable. Build the replacement instead: slice around the position, text[:2] + "m" + text[3:], or convert to a list, assign at the index, and rejoin with "".join(...). Both return a new string and leave the original untouched; validate the index against len(text) when it comes from user input. How to Replace Character in String at Index in Python shows both.

All Python String Guides

Basics

Convert

Clean and Delete

Find, Check and Count

Case, Comparison and Padding

Format and Replace

More string articles

That is the string cluster end to end. For the wider map — lists, dictionaries, files, dates and errors — return to the Python pillar, where the Dictionary and List groups sit alongside the Strings group this page expands.