Python Strings
A string is a piece of text, such as a name, a message or an address.
Creating Strings
Put text inside single quotes '...' or double quotes "...". Both work the same way.
Example
a = 'Hello'
b = "Pakistan"
c = "Ali's laptop"
print(a, b)
print(c)Hello Pakistan Ali's laptop
Use double quotes when the text has an apostrophe inside, like Ali's. For text on several lines, use triple quotes """...""".
Length, Indexing and Slicing
A string is a row of characters. Each character has a position number called an index. Counting starts at 0.
Example
word = "Karachi"
print(len(word))
print(word[0])
print(word[3])
print(word[-1])
print(word[0:4])
print(word[4:])7 K a i Kara chi
| Code | Meaning |
|---|---|
word[0] | First character |
word[-1] | Last character |
word[0:4] | From index 0 up to, but not including, 4 |
word[4:] | From index 4 to the end |
word[:3] | From the start up to index 3 |
Strings are immutable. You cannot change one character with word[0] = "k". Instead, you create a new string.
Joining Strings
Use + to join (concatenate) strings, and * to repeat them:
Example
first = "Ayesha"
last = "Khan"
full = first + " " + last
print(full)
print("-" * 10)Ayesha Khan ----------
f-strings
An f-string lets you put variables and even small calculations inside text:
Example
item = "Biryani"
plates = 3
price = 350
print(f"{plates} plates of {item} cost Rs {plates * price}")
print(f"Average: {85.6666:.2f}")3 plates of Biryani cost Rs 1050 Average: 85.67
:.2f means "show as a decimal number with 2 digits after the point".
Common String Methods
A method is a function that belongs to a value. You call it with a dot.
Example
text = " welcome to workownix "
print(text.upper())
print(text.strip())
print(text.strip().title())
print(text.replace("welcome", "hello"))
print("a,b,c".split(","))
print("python".startswith("py"))
print("Karachi".find("r"))WELCOME TO WORKOWNIX welcome to workownix Welcome To Workownix hello to workownix ['a', 'b', 'c'] True 2
| Method | What it does |
|---|---|
upper() / lower() | All capital / all small letters |
strip() | Removes spaces at both ends |
title() | Capital first letter of each word |
replace(a, b) | Replaces text a with text b |
split(sep) | Breaks the string into a list |
find(x) | Index of x, or -1 if not found |
Checking for Text
Use in to see if some text is inside a string:
Example
address = "Plot 12, Orangi Town, Karachi"
print("Orangi" in address)
print("Lahore" in address)True False
Escape Characters
A backslash \ gives a special meaning to the next character:
Example
print("Line one\nLine two")
print("Name:\tAli")
print("She said \"Salam\"")Line one Line two Name: Ali She said "Salam"
\n is a new line, \t is a tab, and \" is a quote inside the string.
Exercise
Exercise
What does "Python"[1:4] return?
