Strings

Learn everything about strings in Python, how to create, access, slice, and manipulate them using built-in methods like upper(), split(), join(), format(), and more.

Loading...
Strings

What is a String?

A string is a sequence of characters enclosed inside single or double quotation marks.

Strings are one of the most common data types in Python and can contain letters, numbers, symbols, or even spaces.

Creating Strings

You can create a string using either single quotes or double quotes.

name = "John"
city = 'Delhi'

Both are valid.

You can also print them directly:

print("Hello, World!")
print('Hello, Python!')

What If Your String Contains Numbers?

If a string contains numbers, it’s still a string, not a number.

For example:

age = "27"

Even though "27" contains numbers, it is still a string, not the number 27 because it is inside quotation marks.

That difference becomes important when working with numbers.

What If Your String Contains Quotes?

Suppose you want to print:

He said, "I love Python programming!"

You can use single quotes around the string:

print('He said, "I love Python programming!"')

Here, the double quotes are treated as part of the string.

You can also do the opposite:

print("He said, 'I love Python programming!'")
print("It's a beautiful day!")

Using different types of quotes can make your code easier to read.

We can also use \" to include double quotes inside a string, as we learned in Escape Sequence Characters. Switching between single and double quotes, like we did above, is often the cleaner option when possible because it avoids extra backslashes.

A Small Thing to Remember

These are different values:

age = 27

and:

age = "27"

The first one is a number and the second one is a string.

Multiline Strings

Sometimes you need a string that contains multiple lines.

Python lets you create multiline strings using triple quotes.

You can use three single quotes:

message = '''Hello!
Welcome to Python Series.
Let's learn something new today.'''
 
print(message)

Or three double quotes:

message = """Hello!
Welcome to Python Series.
Let's learn something new today."""
 
print(message)

Both work.

The output will be:

Hello!
Welcome to Python Series.
Let's learn something new today.

This is useful when your text needs to span multiple lines.

Accessing Characters in a String

A string is made up of individual characters.

For example:

message = "Hello"

You can access each character using its index.

An index tells Python which position you want.

Python starts counting from 0, not 1.

So:

H → 0
e → 1
l → 2
l → 3
o → 4

You can access a character like this:

print(message[0])
 
# Output:
# H
 
print(message[1])
# Output:
# e

Like this, you can access any character by using its index.

message = "Hello, World!"
 
print(message[0])
print(message[5])
print(message[7])
 
# Output:
 
# H
# ,
# W

Negative Indexing

Python also lets you access characters from the end of a string.

For this, we use negative numbers.

H  e  l  l  o
0  1  2  3  4
-5 -4 -3 -2 -1

So:

message = "Hello"
 
print(message[-1])
 
# Output:
 
# o

-1 means the last character.

Similarly:

message = "Hello"
 
print(message[-2])
 
# Output:
 
# l

Index That Doesn't Exist

If you ask for an index that doesn't exist, Python raises an IndexError.

message = "Hello"
 
print(message[10])
 
# IndexError: string index out of range

Strings Are Immutable

You can read a character using its index, but you can’t change it this way.

message = "Hello"
 
message[0] = "J"
# TypeError: 'str' object does not support item assignment

Strings are immutable, which means once a string is created, you can’t modify it in place.

But you can create modified strings using string methods.

Finding the Length of a String

Python provides the len() function to find how many characters are in a string.

For example:

message = "Hello"
 
print(len(message))
 
# Output:
 
# 5

The length includes everything in the string, including spaces and punctuation.

For example:

message = "Hello, World!"
 
print(len(message))
 
# Output:
 
# 13

String Slicing

Sometimes you don’t want the entire string. You might want only a part of it.

That’s where slicing comes in.

The basic syntax is:

string[start:end]

The start index is included, but the end index is not.

For example:

message = "Hello, World!"
 
print(message[0:5])
 
# Output:
 
# Hello

Here we get Hello, because Python takes characters from index 0 up to, but not including, index 5.

What If the Range Goes Too Far?

Asking for an index that doesn’t exist raises an IndexError.

Slicing behaves differently.

message = "Hello"
 
print(message[0:100])
 
# Output:
 
# Hello

Even though the end index 100 is much larger than the string, Python doesn’t raise an error.

Unlike accessing a single character, slicing simply gives you whatever is available within the string.

This makes slicing a little more forgiving than indexing.

Omitting the Start Index

If you leave out the start index, Python starts from the beginning.

message = "Hello, World!"
 
print(message[:5])
 
# Output:
 
# Hello

This is the same as message[0:5].

Omitting the End Index

You can also leave out the end index.

message = "Hello, World!"
 
print(message[7:])
 
# Output:
 
# World!

This means, start at index 7 and continue to the end.

Using Negative Indexes

You can also use negative indexes when slicing.

message = "Hello, World!"
 
print(message[0:-3])
 
# Output:
 
# Hello, Wor

The -3 means the slice stops three characters from the end.

Or to put it simply, you can understand this like this:

print(message[0:len(message)-3])
 
# message[0:-3] is really message[0:len(message)-3]. 
# Since len(message) is 13, this becomes message[0:10], which gives "Hello, Wor"

Let’s take one more example:

message = "Hello, World!"
 
print(message[-1:])
 
# message[-1:] is really message[len(message)-1:0]. 
# Since len(message) is 13, this becomes message[12:], which gives "!"

Looping Through a String

Strings are iterable, which means you can go through them one character at a time.

You can use a for loop:

message = "Hello"
 
for character in message:
    print(character)
 
# Output:
 
# H
# e
# l
# l
# o

How Does This Work?

Think of the string as a sequence of characters:

H   e   l   l   o

When Python reaches:

for character in message:

it goes through the string one character at a time.

On the first loop:

character → "H"

So this runs:

print(character)

and prints H.

On the next loop:

character → "e"

So Python prints e.

It continues doing this until there are no more characters.

You can think of it like this:

First loop   → H
Second loop  → e
Third loop   → l
Fourth loop  → l
Fifth loop   → o

The loop therefore runs once for every character in the string.

What is character?

character is just a variable name. You could call it something else:

message = "Hello"
 
for letter in message:
    print(letter)

This works exactly the same way.

The important part is:

for variable in string:

Python takes the next character from the string and stores it in that variable for each iteration of the loop.

Another Example

language = "Python"
 
for letter in language:
    print(letter)
 
# Output:
 
# P
# y
# t
# h
# o
# n

Notice that you don’t need to use indexes like 0, 1, 2, and so on.

The for loop handles moving through the string for you.

String Methods

Python provides many built-in methods for working with strings.

String methods are functions that belong to a string and are called using dot notation:

string.method()

For example:

message = "Hello, World!"
 
print(message.upper())
 
# Output:
# HELLO, WORLD!

Here are some of the most useful string methods in Python.

upper()

The upper() method converts all letters in a string to uppercase.

message = "Hello, World!"
 
print(message.upper())
 
# Output:
# HELLO, WORLD!

lower()

The lower() method converts all letters in a string to lowercase.

message = "Hello, World!"
 
print(message.lower())
 
# Output:
# hello, world!

capitalize()

The capitalize() method makes the first character uppercase and converts the remaining characters to lowercase.

message = "hello, WORLD!"
 
print(message.capitalize())
 
# Output:
# Hello, world!

title()

The title() method converts the first character of each word to uppercase.

message = "python is a programming language"
 
print(message.title())
 
# Output:
# Python Is A Programming Language

split()

The split() method breaks a string into smaller parts and returns them as a list.

By default, it splits on whitespace.

message = "Hello World"
 
print(message.split())
 
# Output:
# ['Hello', 'World']

You can also provide a separator:

message = "Hello,World,Python"
 
print(message.split(","))
 
# Output:
# ['Hello', 'World', 'Python']

strip()

The strip() method removes whitespace from the beginning and end of a string.

message = "  Hello, World!  "
 
print(message.strip())
 
# Output:
# Hello, World!

You can also provide specific characters to remove from both ends:

message = "!!!Hello!!!"
 
print(message.strip("!"))
 
# Output:
# Hello

rstrip()

The rstrip() method removes characters from the right side, or end, of a string.

message = "!!!Hello, World!!!"
 
print(message.rstrip("!"))
 
# Output:
# !!!Hello, World

Without an argument, it removes trailing whitespace, from the right side:

message = "   Hello, World!   "
 
print(message.rstrip())

replace()

The replace() method replaces occurrences of one string with another.

message = "Hello, World!"
 
print(message.replace("Hello", "Hi"))
 
# Output:
# Hi, World!

You can also specify how many replacements to make:

message = "apple apple apple"
 
print(message.replace("apple", "orange", 1))
 
# Output:
# orange apple apple

Remember that strings are immutable, so replace() returns a new string rather than changing the original.

center()

The center() method returns a string centered within a specified width.

message = "Hello"
 
print(message.center(20))

The exact spacing depends on the width.

You can also provide a character to use for padding:

message = "Hello"
 
print(message.center(20, "-"))
 
# Output:
# -------Hello--------

count()

The count() method returns the number of times a value appears in a string.

message = "Hello, World!"
 
print(message.count("l"))
 
# Output:
# 3

You can also specify where the search should start and end:

message = "Hello, World!"
 
print(message.count("l", 0, 5))
 
# Output:
# 2

Here, the count will start from the index 0 and end at index 4.

startswith()

The startswith() method checks whether a string starts with a particular value.

It returns True or False.

message = "Hello, World!"
 
print(message.startswith("Hello"))
 
# Output:
# True

endswith()

The endswith() method checks whether a string ends with a particular value.

message = "Hello, World!"
 
print(message.endswith("!"))
 
# Output:
# True

find()

The find() method searches for the first occurrence of a value and returns its index.

message = "Hello, World!"
 
print(message.find("W"))
 
# Output:
# 7

If the value isn't found, find() returns -1.

print(message.find("Python"))
 
# Output:
# -1

index()

The index() method also searches for the first occurrence of a value and returns its index.

message = "Hello, World!"
 
print(message.index("W"))
 
# Output:
# 7

The difference between find() and index() is what happens when the value isn't found.

find() returns -1:

message.find("Python")

index() raises a ValueError:

message.index("Python")

So:

  • find() → -1 when not found
  • index() → ValueError when not found

Use find() when the value might normally be missing and you want to handle that case yourself.

Use index() when the value is expected to be there and its absence means something went wrong. The ValueError makes the problem visible immediately instead of returning -1.

isalnum()

The isalnum() method returns True if all characters in the string are letters or numbers and there is at least one character.

message = "Hello123"
 
print(message.isalnum())
 
# Output:
# True

A space or punctuation mark makes it return False:

message = "Hello 123"
 
print(message.isalnum())
 
# Output:
# False

isalpha()

The isalpha() method returns True if all characters in the string are alphabetic and there is at least one character.

message = "HelloWorld"
 
print(message.isalpha())
 
# Output:
# True

Numbers, spaces, and punctuation make it return False.

message = "Hello123"
 
print(message.isalpha())
 
# Output:
# False

isupper()

The isupper() method returns True if all cased characters in the string are uppercase and there is at least one cased character.

message = "HELLO"
 
print(message.isupper())
 
# Output:
# True

islower()

The islower() method returns True if all cased characters in the string are lowercase and there is at least one cased character.

message = "hello"
 
print(message.islower())
 
# Output:
# True

isprintable()

The isprintable() method returns True if all characters in the string are printable.

message = "Hello, World!"
 
print(message.isprintable())
 
# Output:
# True

Characters such as newline and tab are not printable:

message = "Hello\nWorld"
 
print(message.isprintable())
 
# Output:
# False

isspace()

The isspace() method returns True if the string contains only whitespace characters and contains at least one character.

message = "    "
 
print(message.isspace())
 
# Output:
# True

A string containing letters is not considered whitespace:

message = "Hello"
 
print(message.isspace())
 
# Output:
# False

istitle()

The istitle() method returns True if the string is title-cased.

message = "World Health Organization"
 
print(message.istitle())
 
# Output:
# True
message = "hello world"
 
print(message.istitle())
 
# Output:
# False

swapcase()

The swapcase() method changes uppercase characters to lowercase and lowercase characters to uppercase.

message = "Hello, World!"
 
print(message.swapcase())
 
# Output:
# hELLO, wORLD!

Strings Are Immutable

String methods don't modify the original string in place.

For example:

message = "hello"
 
message.upper()
 
print(message)
 
# Output:
# hello

If you want to keep the result, assign it to a variable:

message = "hello"
 
message = message.upper()
 
print(message)
 
# Output:
# HELLO

The same idea applies to methods such as replace(), strip(), and lower().

Quick Reference

Method What it does
upper() Converts letters to uppercase
lower() Converts letters to lowercase
capitalize() Capitalizes the first character and lowercases the rest
title() Capitalizes each word
split() Splits a string into a list
strip() Removes characters/whitespace from both ends
rstrip() Removes characters/whitespace from the right
replace() Replaces text
center() Centers a string within a given width
count() Counts occurrences
startswith() Checks the beginning
endswith() Checks the end
find() Finds a value and returns -1 if not found
index() Finds a value and raises ValueError if not found
isalnum() Checks whether all characters are letters or numbers
isalpha() Checks whether all characters are alphabetic
isupper() Checks whether cased characters are uppercase
islower() Checks whether cased characters are lowercase
isprintable() Checks whether all characters are printable
isspace() Checks whether all characters are whitespace
istitle() Checks whether the string is title-cased
swapcase() Swaps uppercase and lowercase characters

You don't need to memorize all of these.

The more you work with Python, the more naturally you'll remember the methods you use often. Keep this page as a reference when you need a method you haven't used before.


👉 Next tutorial: Python Conditional Statements