Python Strings

In Python, strings are used to store text data. A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes.
Strings are one of the most commonly used data types in Python.

What Is a String?

A string is a collection of characters such as:
  • Letters
  • Numbers
  • Symbols
  • Spaces
python
text = "Hello Python"
python
name = 'John'
python
message = "Welcome to Python Programming"

Creating Strings in Python

Strings can be created using:
  • Single quotes (' ')
  • Double quotes (" ")
  • Triple quotes (''' ''' or """ """)

Single Quotes

python
language = 'Python'

Double Quotes

python
language = "Python"

Triple Quotes (Multi-line Strings)

python
text = """Python is easy
Python is powerful
Python is popular"""
print(text)

Strings Are Immutable

Strings in Python are immutable, which means they cannot be changed after creation.
python
text = "Python"
# text[0] = "J"  # Error
python
text = "Python"
text = "Java"
print(text)

String Indexing

Each character in a string has an index position starting from 0.
python
text = "Python"
print(text[0])
python
print(text[3])
python
print(text[-1])

String Slicing

Slicing is used to extract a portion of a string.
python
text = "Python"
print(text[0:3])
python
print(text[2:5])
python
print(text[:4])

String Length

The len() function is used to find the length of a string.
python
text = "Python"
print(len(text))
python
name = "Programming"
print(len(name))
python
print(len("Hello World"))

String Concatenation

Strings can be joined using the + operator.
python
a = "Hello"
b = "Python"
print(a + " " + b)
python
first = "Code"
second = "Marathi"
print(first + second)
python
print("AWS" + " Cloud")

String Repetition

Strings can be repeated using the * operator.
python
print("Python " * 3)
python
star = "*"
print(star * 10)
python
print("Hi " * 2)

String Formatting

Using Comma

python
name = "John"
age = 25
print("Name:", name, "Age:", age)

Using f-strings (Recommended)

python
name = "John"
age = 25
print(f"Name is {name} and age is {age}")
python
a = 5
b = 10
print(f"Sum is {a + b}")

Common String Methods

python
text = "python"
print(text.upper())
python
print(text.lower())
python
print(text.capitalize())
python
print(text.replace("p", "P"))

Checking Substrings

python
text = "Python Programming"
print("Python" in text)
python
print("Java" in text)
python
print("gram" in text)

Summary

  • Strings store text data
  • Strings are immutable
  • Indexing starts from 0
  • Slicing extracts parts of a string
  • len() finds string length
  • Strings support many useful methods

Exercise

  • Create a string and print its length
  • Extract first three characters
  • Convert a string to uppercase