Working with strings
Text is everywhere: names, messages, files, web pages. Python's strings (str) come with dozens of useful built-in tools.
Creating strings
f-strings: building text from values
Indexing and slicing
A string is a sequence of characters, numbered from 0. Negative numbers count from the end:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1Strings are immutable: you can't change a character in place. Methods return a new string:
Useful string methods
Splitting and joining
split breaks a string into a list; join glues a list back together:
Checking for text
Looping over characters
A small program: initials and a username
Practice
- Ask for a sentence (Input box) and print how many words it has, and the longest word. (Hint:
max(words, key=len).) - Turn
"2025-03-14"into"14/03/2025"usingsplitand an f-string. - Print a word reversed and in upper case.
✎ Check your understanding
1.What does "Python"[1:4] give?
2.What does "a,b,c".split(",") return?
3.Why does word[0] = "J" fail?