Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Strings

A string is a piece of text: a name, a sentence, a line of a file. In Python a string is written between single quotes '...' or double quotes "..."; both mean exactly the same. Strings are one of the most used types, and Python gives you many ways to work with them.

Creating strings

city = "Pune"
greeting = 'Hello'
poem = """Roses are red,
violets are blue."""
print(greeting, city)
print(poem)
print(len(city), len(poem))
Output
Hello Pune
Roses are red,
violets are blue.
4 32

Three quotes, """ or ''', make a string that can span several lines. len gives the number of characters, and a new line counts as one character.

Indexing and slicing

Each character has a position called its index, starting at 0. Negative indexes count from the end: -1 is the last character. A slice [start:stop] takes the characters from start up to, but not including, stop:

word = "Python"
print(word[0], word[1], word[-1])
print(word[0:3])
print(word[2:])
print(word[:2])
print(word[::-1])
Output
P y n
Pyt
thon
Py
nohtyP

Leaving out start means "from the beginning", leaving out stop means "to the end", and a third number is the step: [::-1] walks backwards, which reverses the string. Asking for an index that does not exist, such as word[10], is an IndexError, but a slice that goes too far is simply shortened.

Joining, repeating and checking

first, last = "Ada", "Lovelace"
full = first + " " + last
print(full)
print("-" * 20)
print("love" in full.lower(), "x" in full)
Output
Ada Lovelace
--------------------
True False

+ joins strings, * repeats a string, and in checks whether one string appears inside another.

Strings cannot change

Strings are immutable: once created, a string cannot be changed. word[0] = "J" is an error. Instead, you build a new string, for example "J" + word[1:], and assign it to a variable. All the string methods in the next topic work this way: they return a new string and leave the old one as it was.

Practice exercises

  1. Store your full name in a variable and print its first letter, its last letter and its length.
  2. Print the first three and the last three characters of "Programming" with slices.
  3. Check whether a word is a palindrome (the same backwards) with word == word[::-1].
  4. Print a line of 30 equals signs with *.