Definition
How do you turn " RIYA sharma " into "Riya Sharma"?
String methods are built-in functions attached to strings, called with a dot, such as text.upper(). They return a new, changed string. f-strings, written f"…{value}…", insert values into text and can format numbers, for example to two decimal places.
In simple words
strip() trims spaces from the ends, lower() and upper() change case, title() capitalises each word, replace() swaps one piece of text for another, and split() breaks a sentence into a list of words. join() does the reverse. f"{name} scored {marks}" builds a sentence from variables.
Overview
- A method is a function that belongs to an object and is called with a dot: text.upper().
- String methods never change the original string; they return a new one.
- Methods can be chained: name.strip().title().
- Formatting builds readable output by placing values inside text with control over decimals and alignment.
- f-strings (Python 3.6+) are the modern, recommended way to format.
- Cleaning text with these methods is the first step of every NLP pipeline.
Why it matters
Real text is messy: extra spaces, mixed case, typos. Cleaning it is the first step before any analysis or AI model can use it, and clear formatted output makes results easy to read.
Key terms
- Method
- A function attached to a value and called with a dot, such as text.upper().
- f-string
- A string starting with f that inserts values written inside curly braces.
- Format specifier
- Instructions after a colon inside an f-string, such as :.2f for two decimal places.
- split()
- Breaks a string into a list of parts.
- join()
- Glues a list of strings together with a separator.
- Method chaining
- Calling several methods in a row, such as text.strip().lower().
Types
Python has over 40 string methods. They fall into a few families by purpose, and there are three styles of formatting. These are the types.
1. Case methods
upper(), lower(), title(), capitalize(), swapcase() and casefold().
- How it works: They return a copy with letters changed to the requested case; casefold() is a stronger lower() for comparing text in any language.
- Example: "aarav sharma".title() gives "Aarav Sharma".
- When to use it: Use them to tidy names and to compare user input without worrying about capitals.
2. Search and test methods
find(), index(), count(), startswith(), endswith() and the is-methods such as isdigit(), isalpha() and isspace().
- How it works: find() returns a position or -1; count() counts occurrences; is-methods return True or False about every character.
- Example: "9876543210".isdigit() is True; "report.pdf".endswith(".pdf") is True.
- When to use it: Use them to validate input such as phone numbers and to find words in text.
3. Cleaning and replacing methods
strip(), lstrip(), rstrip(), replace() and the padding methods center(), ljust(), rjust() and zfill().
- How it works: strip() removes spaces (or chosen characters) from the ends; replace(old, new) swaps every occurrence; zfill() pads with zeros.
- Example: " Pune ".strip() is "Pune"; "7".zfill(3) is "007".
- When to use it: Use them to clean messy input from forms and files before analysis.
4. Splitting and joining methods
split(), rsplit(), splitlines() and join().
- How it works: split(sep) breaks a string into a list at each separator (spaces by default); "sep".join(list) glues a list of strings together.
- Example: "red,green,blue".split(",") gives a list of 3 colours; "-".join(["2024", "08", "15"]) gives "2024-08-15".
- When to use it: Use them to turn sentences into words and CSV lines into fields, and back.
5. f-string formatting
Strings starting with f where {expression:format} is replaced by a formatted value.
- How it works: After the colon, codes set decimals (.2f), width (8), alignment (< ^ >), thousands separators (,) and percentages (%).
- Example: f"{name:<10}{marks:>5}" aligns a table; f"{0.825:.1%}" gives 82.5%.
- When to use it: Use it for all new code: it is the fastest and easiest to read.
6. Older formatting: str.format() and %
"{} scored {}".format(name, marks) and the C-style "%s scored %d" % (name, marks).
- How it works: Placeholders are filled from the arguments in order or by name, with the same format codes as f-strings.
- Example: "{:.2f}".format(3.14159) gives "3.14".
- When to use it: Recognise them in older code and libraries; format() is still useful when the template is stored separately from the values.
Explained in detail
Cleaning text
Real text is messy: extra spaces, mixed capitals, unexpected punctuation. String methods tidy it. strip() removes spaces and new lines from both ends; lower() and upper() change case; replace("old", "new") swaps every occurrence. Because each method returns a new string, you can chain them: answer.strip().lower() turns " YES " into "yes", so a chatbot can recognise the answer however it was typed. This kind of normalising is the first step in almost every text-processing task in AI.
Searching and testing
| Method | Example | Result |
|---|---|---|
| find() | "banana".find("an") | 1 (first position), or -1 if absent |
| count() | "banana".count("a") | 3 |
| startswith() | "+91 98".startswith("+91") | True |
| isdigit() | "2024".isdigit() | True |
| split() | "a,b,c".split(",") | ["a", "b", "c"] |
| join() | " - ".join(["a", "b"]) | "a - b" |
split() with no argument splits on any run of whitespace, which makes it the quickest way to break a sentence into words. join() is its partner: it is called on the separator, not the list, which surprises people at first but reads naturally once you are used to it.
Formatting with f-strings
Introduced in Python 3.6 in 2016, f-strings are now the standard way to build text from values. Inside f"…", anything in braces is evaluated: f"{name} scored {mark}". After a colon you can add a format specifier. :.2f shows two decimal places, so f"{72.456:.2f}" gives 72.46. :, adds thousands separators, :% shows a fraction as a percentage, and :>8 right-aligns in a column eight characters wide, which is how neat reports and tables are printed. Since Python 3.8, f"{x=}" prints both the expression and its value, a handy debugging shortcut.
- Clean: strip() and lower() the raw text.
- Split: break it into words or fields.
- Test: use in, startswith() or isdigit() to decide what to do.
- Format: build the output with an f-string.
You will also see two older styles in existing programs: the % operator, as in "%s scored %d" % (name, mark), and the format() method, as in "{} scored {}".format(name, mark). Both still work, and you should recognise them when reading other people's work, but for anything new, f-strings are shorter and clearer. When reports must line up in columns, combine width and alignment specifiers: f"{name:<10}{mark:>5}" left-aligns a name in ten characters and right-aligns a mark in five, which is how the marks analyser project prints its neat table.
How it works
| Method | Example | Result |
|---|---|---|
| strip() | " hi ".strip() | "hi" |
| lower() / upper() | "Ai".upper() | "AI" |
| title() | "riya sharma".title() | "Riya Sharma" |
| replace() | "cat".replace("c", "b") | "bat" |
| split() | "a b c".split() | ["a", "b", "c"] |
| join() | "-".join(["a", "b"]) | "a-b" |
| f-string | f"{2/3:.2f}" | "0.67" |
In code
Cleaning a messy name, counting words, and formatting a report line.
raw = " RIYA sharma "
clean = raw.strip().title()
print("Clean name:", clean)
sentence = "AI is fun and AI is useful"
words = sentence.split()
print("Words:", words)
print("Number of words:", len(words))
print("Times 'AI' appears:", sentence.count("AI"))
print("Joined with dashes:", "-".join(words[:3]))
marks, total = 47, 60
print(f"{clean} scored {marks}/{total} = {marks / total * 100:.1f}%")Output
Clean name: Riya Sharma Words: ['AI', 'is', 'fun', 'and', 'AI', 'is', 'useful'] Number of words: 7 Times 'AI' appears: 2 Joined with dashes: AI-is-fun Riya Sharma scored 47/60 = 78.3%
Try it yourself
Which method?
Match each job to the method that does it.
- Remove spaces from both ends
- Make every letter capital
- Break a sentence into words
- Swap one word for another
- Glue a list of words with a separator
Common mistakes
- Expecting a method to change the original string. Store the result: name = name.strip().
- Forgetting the f before an f-string, so {name} is printed literally.
- Calling join on the list instead of the separator: it's "-".join(words).
Check yourself
Summary
- Methods such as strip, lower, title, replace and split clean text.
- They return new strings; store the result.
- f-strings insert and format values neatly.
Finished reading?
Sources: W3Schools: Python String Methods