Strings
s = "Python"Each character has a position, called its index. Counting starts at 0.
1Level 1 · BasicsBasics
A string is a piece of text: a name, a sentence, even a whole book. Strings are everywhere in programs, so Python gives you lots of tools to work with them.
Creating strings
Use single or double quotes. Triple quotes ("""...""") let a string span several lines. To put a quote inside, use the other kind: "It's fine".
Indexing: one character at a time
Each character has a position called an index, and counting starts at 0:
P y t h o n 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1
s[0] is "P". Negative indexes count from the end, so s[-1] is the last character, "n". len(s) gives the length (6).
Slicing: a piece of a string
s[start:stop] takes characters from start up to but not including stop:
s = "Python" s[0:3] # "Pyt" s[2:] # "thon" (to the end) s[:2] # "Py" (from the start) s[::-1] # "nohtyP" (step -1 reverses)
Useful string methods
| Method | What it does |
|---|---|
s.upper(), s.lower(), s.title() | change case |
s.strip() | remove spaces from both ends |
s.replace("a", "b") | replace text |
s.split() | split into a list of words |
" ".join(words) | join a list back into one string |
s.find("x"), s.count("x") | position of / number of occurrences |
s.startswith("x"), s.isdigit() | yes/no checks |
Strings can't be changed
Strings are immutable: methods like upper() return a new string and leave the original alone. To keep the result, store it: name = name.upper().
Checking and looping
"py" in "python" is True. A for loop visits each character: for ch in s:. You'll meet loops properly two lessons from now.
Key points: indexes start at 0 and negative ones count from the end; slices stop before the stop index; methods return new strings; use in to search.See it in actionIndexing and slicing a string
See how positions start at 0 and how methods build new strings.
Try it yourselfExample 1: Indexing and slicing
Try other numbers in the brackets. What happens with s[10]?
Output appears hereFirst and last
Fill the blanks so the program prints the first letter and the last letter of Python: P n.
word = "Python" print(word[], word[])
Changing one letter
This should turn cat into bat and print it, but it crashes. Fix it.
Example 2: Cleaning up text
Methods return new strings, so we can chain them one after another.
Output appears hereClean up a name
Fill the blanks so " rIMa " becomes Rima: remove the spaces, then fix the capitals.
name = " rIMa " print(name.().())
Example 3: Split and join
split() cuts a sentence into separate words (the square brackets show them as a list, which you'll meet in the Lists lesson); join() glues the words back together.
Output appears hereInitials
Read a full name like Sadia Rahman Khan and print the initials in capitals: SRK.
Example inputSadia Rahman KhanExpected outputSRK
Example 4: Searching in a string
in, find() and count() answer "is it there?", "where?" and "how many?".
Output appears hereCount the vowels
Read a word and print how many vowels (a, e, i, o, u) it has, ignoring capitals. Banana gives 3.
Example inputBananaExpected output3
2Level 2 · IntermediateSlicing tricks and text processing
Steps and negative steps
s[::2] takes every second character; s[::-1] reverses the string. A palindrome check is just s == s[::-1].
Counting and replacing
s.count("a"), s.replace("old", "new"), s.startswith("Dr."), s.endswith(".py"), s.isdigit(), s.isalpha() answer most everyday questions.
Finding text
s.find("x") gives the position of the first match, or -1 when there is none. "x" in s just answers yes or no.
Characters are numbers
ord("A") is 65 and chr(66) is "B". That's how a Caesar cipher shifts letters.
See it in actionReversing and checking a palindrome
Watch the cleaned text and its reverse appear, then the comparison.
Example 5: Shifting a letter, Caesar style
Change letter to "Y" and see it wrap around to the start of the alphabet. In the Loops lesson you'll shift every letter of a whole message.
Output appears hereExample 6: Text statistics
Paste your own sentence into text.
Output appears here3Level 3 · AdvancedUnicode, encoding and advanced formatting
Strings are Unicode
A Python string holds characters, not bytes, so Bangla works naturally: len("বাংলা") counts code points. Some letters are built from several code points (a consonant plus a vowel sign), so the count can be larger than what you see.
Bytes and encodings
s.encode("utf-8") turns text into bytes for files and networks; b.decode("utf-8") goes back. English letters take 1 byte, Bangla letters 3.
str.translate and str.maketrans
Replace many characters in one pass, for example English digits to Bangla digits.
Templates and nested format specs
Widths can come from variables: f"{name:<{width}}". f"{value=}" prints both the expression and its value, which is great for debugging.
Example 7: Bangla text, bytes and digits
translate() changes every digit in one pass.
Output appears hereExample 8: Dynamic widths and self-documenting f-strings
The table widens to fit the longest name automatically.
Output appears heres[0] = "J" raises a TypeError because strings can't be changed in place. Build a new one instead: s = "J" + s[1:].What does this print?
s = "programming" print(s[3:7])
50 graded problems are waiting in Topic Practice.