Strings
Basics8 min readLesson 4 of 8
A string is a sequence of characters, written between single or double quotes. Both quote styles do the same job, so choose one and stay consistent inside a line. Strings can hold letters, digits, spaces, punctuation, or no characters at all. Characters in a string cannot be changed in place, but a name can be rebound to a new string. Names, messages, and file contents arrive as text, so string handling appears in most programs.
name = 'Maya'
greeting = 'Hello, ' + name
print(greeting)
print(name[0])
print(len(name))Output
Hello, Maya M 4
4.1 Indexing and slicing
Indexing counts from zero, so word[0] is the first character and word[-1] is the last. A slice such as word[1:4] includes the start index and stops before the end index. Slicing past the end is safer than indexing past the end: s[0:100] returns the available characters, while s[100] raises IndexError.
4.2 Joining and formatting
+joins two strings.*repeats a string:'ha' * 3gives'hahaha'.upper(),lower(), andstrip()return a new string.
An f-string such as f'Total: {amount}' converts values for display while keeping the sentence readable.
item = 'notebook'
price = 45
label = f'{item}: {price} rupees'
print(label)
print(label.upper())Output
notebook: 45 rupees NOTEBOOK: 45 RUPEES
4.3 Common mistake
Joining text and a number with + fails. The expression 'Age: ' + 15 raises TypeError because the left side expects another string. Use an f-string or str(15) to make the number part of the text before joining.
word = 'python'
print(word[0:3])
print(word[-3:])
print(word * 2)
print(word.upper())Output
pyt hon pythonpython PYTHON
4.4 Practice
- Store your full name with extra spaces around it.
- Print the cleaned name and its length, then print the first three characters.
- Add an f-string that prints the name and your age in a sentence.
If you need literal quote marks inside a string, use the other quote type on the outside or escape them with a backslash.
