← Winnitude! Search  ·  Reader Mode (253 ms)
Links: Stay in Reader Retro Site Converter Retro Mode: OFF Original Page ↗
PROGRAMIZ · 86 LINKS

Python Strings | Programiz

Online Python Online JavaScript Online SQL Online Java Online HTML Online C Online C++ Online C# Online PHP Online Swift Online Kotlin Online TypeScript Online Go Online Rust Online Scala Online Dart Online R Online Ruby

Popular Tutorials

Getting Started With Python Python if Statement while Loop in Python Python Lists Dictionaries in Python Start Learning Python

Reference Materials

Built-in Functions List Methods Dictionary Methods String Methods View all

Certification Courses

Created with over a decade of experience and thousands of feedback.

Learn Python Learn HTML Learn JavaScript Learn SQL Learn DSA Learn C Learn C++ Learn Java View all Courses on

Popular Tutorials

Getting Started With Python Python if Statement while Loop in Python Python Lists Dictionaries in Python Start Learning Python All Python Tutorials

Reference Materials

Built-in Functions List Methods Dictionary Methods String Methods View all Python online compiler JavaScript online compiler SQL online compiler Java online compiler HTML online compiler C online compiler C++ online compiler C# online compiler PHP online compiler Swift online compiler Kotlin online compiler TypeScript online compiler Go online compiler Rust online compiler Scala online compiler Dart online compiler R online compiler Ruby online compiler

Python Strings

In this article, we will learn about the Python Strings with the help of examples.

A string is a sequence of characters enclosed inside quotes (either double or single quotes). It is used to store and work with textual data in any language or symbol set supported by Unicode.

For example, 'Opus' (same as "Opus") is a string that contains characters 'O', 'p', 'u' and 's'. By the way, these single characters are also strings themselves.


Python Multiline Strings

If we need to create a string containing multiple lines, we use triple double quotes """ or triple single quotes '''. For example,

# Multiline string
message = """To avoid pain, they avoid pleasure.
To avoid death, they avoid life."""

print(message)

Output

To avoid pain, they avoid pleasure.
To avoid death, they avoid life.

Access String Characters

A string is a sequence, like a list or a tuple. This means characters in a string are ordered, and each one is associated with an integer, known as index .

Index of first character is 0 , index of second character is 1 , and so on.

model = 'ChatGPT'

# Access the first character
print(model[0])    # Output: C

# Access the fifth character
print(model[4])    # Output: G

Similar to other sequences in Python, strings also support negative indexing. Index of last character is -1 , index of second last character is -2 , and so on.

model = 'ChatGPT'

# Access the last character
print(model[-1])   # Output: T

# Access the fourth last character
print(model[-4])   # Output: t
Python string indexing
String Indexing

If we try to access a character outside index range, we get an IndexError.

model = 'ChatGPT'
print(model[8])       # IndexError

We can access a portion of a string (or any sequence) using colon : operator, known as slicing.

model = 'ChatGPT'

# Access characters from index 0 up to (but not including) 4
print(model[0:4])   # Output: Chat

You can learn more about it in Python slicing tutorial .


Strings are Immutable

In Python, strings are immutable; we cannot modify them. For example,

model = 'ChatGPT'

model[0] = 'W'
print(model)

Output

TypeError: 'str' object does not support item assignment

However, what we can do is create a modified version of the original string and assign it to a variable, without modifying the original string itself.

model = 'Opus'
version = '5'

model = model + " " + version
print(model)    # Opus 5

In this program, we are concatenating strings 'Opus', ' ' and '5' using + operator to create a new string. Note that we are not modifying strings 'Opus', ' ' and '5'; that's not possible.


Python String Methods

Python provides many string methods out of the box that make it easy to manipulate strings. For example, replace() method,

text = "ChatGPT is great."

# Replace "ChatGPT" with "Claude"
new_text = text.replace("ChatGPT", "Claude")

print(new_text)  # Output: Claude is great.

Here, replace() method returns a new string with "ChatGPT" replaced by "Claude".

You can find a list of all string methods and their respective tutorials here .


String Membership Test

We can test if a substring exists within a string or not using in keyword.

print('Chat' in 'ChatGPT')        # True
print('Claude' not in 'ChatGPT')  # True

Iterate Through a String

Since a string is a sequence of characters, we can iterate through it using a for loop . For example,

model = 'Opus'

for c in model:
    print(c)

Output

O
p
u
s

Python String Length

Besides string methods, Python has many built-in functions that provide different functionalities. One such commonly used function is len() , which returns length (number of characters) of a string. For example,

model = 'Opus'

# Count the number of characters
print(len(model))   # Output: 4

Escape Sequences

Escape sequences are used to include certain characters, such as quotes and newlines, inside a string.

Suppose a string has both single and double quotation marks as its characters. In such case, we can't do something like this:

example = "He said, "What's there?""

print(example) # Error

Here, Python interpreter treats "He said, " as a string and doesn't know how to interpret the rest of the text. Hence, above code results in an error.

To solve this issue, we use escape character \ in Python.

# escape double quotes
example = "He said, \"What's there?\""

# escape single quotes
example = 'He said, "What\'s there?"'

print(example)

# Output: He said, "What's there?"

Here are some commonly used escape sequences:

Escape Sequence Description
\\ Backslash
\' Single quote
\" Double quote
\b ASCII Backspace
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab

String Formatting (f-Strings)

Python f-strings are used to create a new string by combining values and variables.

An f-string starts with f followed by a string inside quotation marks. Curly braces {} act as placeholders where you can insert variables or expressions directly.

company = 'Google'
field = 'AI'

message = f'{company} is an {field} company.'
print(message)

Output

Google is an AI company.

Share on: Did you find this article helpful?

Table of Contents

Related Tutorials

Python Tutorial

Python Iterators

Python Tutorial

Python datetime

Python Tutorial

Python Dictionary

Python Tutorial

Python Programming Built-in Functions