Python Strings

A string is a sequence of characters, like a word, a sentence or even a whole paragraph. In Python a string is written inside single quotes or double quotes. Strings are one of the most used data types in every program.


Create a string

You can use single quotes, double quotes, or triple quotes. Triple quotes are used for a string that runs on many lines.

a = 'Hello'
b = "World"
c = """This is
a multi-line
string"""

print(a, b)
print(c)
Output of the above program is

Hello World
This is
a multi-line
string


Indexing and slicing

Every character has a position (index) that starts from 0. Negative index starts from the end, so -1 is the last character. A slice text[start:end] gives the characters from start up to, but not including, end.

text = "Python"

print(text[0])
print(text[-1])
print(text[0:3])
print(text[2:])
print(text[::-1])
Output of the above program is

P
n
Pyt
thon
nohtyP

The last line uses a step of -1, which reverses the string. See also negative index.


Length and membership

text = "Python"

print(len(text))
print("th" in text)
print("z" not in text)
Output of the above program is

6
True
True


Strings are immutable

You cannot change a character of a string after it is created. You have to create a new string.

text = "Python"
text[0] = "J"
Output of the above program is

TypeError: 'str' object does not support item assignment

text = "Python"
text = "J" + text[1:]
print(text)
Output of the above program is

Jython


Common string methods

String methods do not change the original string. They return a new value.

MethodUse
upper(), lower()Change the case
title(), capitalize()Capital letter for each word / only for the first letter
strip()Remove spaces from both ends
replace(old, new)Replace a part of the string
split(sep)Break the string into a list
join(list)Join a list into a string
find(text)Position of the text, or -1 if not found
count(text)How many times the text comes
startswith(), endswith()Check the start or the end
isdigit(), isalpha()Check if only digits / only letters
s = "hello python"

print(s.upper())
print(s.title())
print(s.capitalize())
print(s.replace("python", "world"))
print(s.split())
print(s.find("python"))
print(s.count("o"))
print(s.startswith("hello"))
print(s.endswith("n"))
print("  hi  ".strip())
print("42".isdigit())
print("-".join(["a", "b", "c"]))
Output of the above program is

HELLO PYTHON
Hello Python
Hello python
hello world
['hello', 'python']
6
2
True
True
hi
True
a-b-c

To know more about two of them, read join() and upper().


Join and repeat strings

print("Py" + "thon")
print("ab" * 3)
Output of the above program is

Python
ababab


Formatting with f-strings

An f-string lets you put variables inside a string with curly braces. It is the easiest way to format text (Python 3.6 and above). See What are f-strings?

name = "Robin"
age = 20
print(f"{name} is {age} years old")
Output of the above program is

Robin is 20 years old


Escape characters

A backslash \ inside a string gives a special meaning to the next character.

CodeResult
\nNew line
\tTab space
\\One backslash
\"A double quote inside a double quoted string
\'A single quote inside a single quoted string
print("Line one\nLine two")
print("She said \"Hi\"")
print("C:\\folder")
print(r"C:\new\table")
Output of the above program is

Line one
Line two
She said "Hi"
C:\folder
C:\new\table

A string that starts with r is a raw string, where backslashes are kept as they are. It is useful for file paths.


Loop through a string

for ch in "abc":
    print(ch)
Output of the above program is

a
b
c


Compare strings

print("apple" == "apple")
print("apple" == "Apple")
print("a" < "b")
Output of the above program is

True
False
True

Comparison is case-sensitive. To ignore case, change both strings to lower case first.


Summary

  • A string is a sequence of characters inside quotes.
  • Use index and slicing to get a part of a string.
  • Strings cannot be changed. Methods return a new string.
  • Use f-strings for formatting.
  • Use backslash for special characters and r"" for raw strings.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.