PYnative

Practice Coding

  • Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQs▼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilers▼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » Strings in Python: A Complete Guide With Examples

Strings in Python: A Complete Guide With Examples

Updated on: December 4, 2026 | Leave a Comment

A string is a sequence of characters used to store text, such as a name, a sentence, an email address, or the contents of a file. Strings are one of the most used data types in Python. Almost every program reads, builds, cleans, or prints text.

In this guide, you’ll learn how to create strings, access their characters, combine and compare them, work with special characters, and avoid the mistakes beginners make most often.

Key terms used in this article:

  • String: An ordered, immutable sequence of Unicode characters. Its type is str.
  • Character: A single letter, digit, symbol, space, or emoji. Python has no separate character type: a character is a string of length 1.
  • Index: The position of a character in a string. The first character is at index 0.
  • Immutable: Can’t be changed after it’s created. String methods return new strings instead of changing the original.
  • Escape sequence: A backslash followed by a character, such as \n (new line), that represents a special character.

Table of contents

  • Creating strings
    • Multi-line strings
    • Creating strings from other values
  • Escape sequences
  • Raw strings
  • Accessing characters with indexing
  • Slicing strings
  • Strings are immutable
  • String operations
    • Concatenation and repetition
    • Length, membership, and counting
    • Comparing strings
  • Looping through a string
  • Common string methods
  • Splitting and joining strings
  • Formatting strings
  • Checking the content of a string
  • Unicode, encoding, and bytes
  • Building strings efficiently
  • Useful constants in the string module
  • Common mistakes
  • Practice exercises
  • Summary

Creating strings

Wrap text in single quotes, double quotes, or triple quotes. Single and double quotes behave exactly the same:

name = 'Jessa'
city = "London"
empty = ""

print(name, city)
print(type(name))
print(len(empty))Code language: Python (python)

Output:

Jessa London
<class 'str'>
0

Choose the quote style that avoids escaping. Use double quotes when the text contains an apostrophe, and single quotes when it contains double quotes:

sentence = "It's a sunny day"
quote = 'She said "hello" to me'
print(sentence)
print(quote)Code language: Python (python)

Output:

It's a sunny day
She said "hello" to me

Multi-line strings

Triple quotes (""" or ''') let a string span several lines. The line breaks are kept in the string:

address = """PYnative
221B Baker Street
London"""
print(address)Code language: Python (python)

Output:

PYnative
221B Baker Street
London

Triple-quoted strings are also used for docstrings, the documentation strings at the top of functions, classes, and modules.

Creating strings from other values

str() converts almost any value to a string:

age = 28
price = 9.99
items = [1, 2, 3]

print(str(age) + " years")
print("Price: " + str(price))
print(str(items))
print(str(True))Code language: Python (python)

Output:

28 years
Price: 9.99
[1, 2, 3]
True

Escape sequences

A backslash \ starts an escape sequence, which represents a character that’s hard to type directly.

Escape sequenceMeaning
\nNew line
\tTab
\\Backslash
\'Single quote
\"Double quote
\rCarriage return
\uXXXXUnicode character by hex code, such as \u20ac for €
\N{name}Unicode character by name, such as \N{GREEK SMALL LETTER PI}
print("Line 1\nLine 2")
print("Name:\tJessa")
print("C:\\Users\\Jessa")
print('It\'s fine')
print("Price: \u20ac9.99")
print("Circle area = \N{GREEK SMALL LETTER PI} r\N{SUPERSCRIPT TWO}")Code language: Python (python)

Output:

Line 1
Line 2
Name:	Jessa
C:\Users\Jessa
It's fine
Price: €9.99
Circle area = π r²

Raw strings

Prefix a string with r to create a raw string, where backslashes are treated as normal characters. Raw strings are ideal for Windows paths and regular expressions:

normal = "C:\new_folder\test.txt"
raw = r"C:\new_folder\test.txt"

print(normal)  # \n and \t were turned into a newline and a tab
print(raw)Code language: Python (python)

Output:

C:
ew_folder	est.txt
C:\new_folder\test.txt

A raw string can’t end with an odd number of backslashes, so r"C:\folder\" is a SyntaxError. Use "C:\\folder\\" or add the trailing backslash separately.

Accessing characters with indexing

Each character has a position called an index. Python counts from 0 from the left, and from -1 from the right:

 P   y   t   h   o   n
 0   1   2   3   4   5
-6  -5  -4  -3  -2  -1
word = "Python"

print(word[0])    # first character
print(word[3])
print(word[-1])   # last character
print(word[-2])
print(word[len(word) - 1])Code language: Python (python)

Output:

P
h
n
o
n

Using an index that doesn’t exist raises an IndexError:

word = "Python"
try:
    print(word[10])
except IndexError as error:
    print("Error:", error)Code language: Python (python)

Output:

Error: string index out of range

Slicing strings

A slice extracts part of a string with the syntax string[start:stop:step]. The start index is included and the stop index is excluded:

text = "Hello, World"

print(text[0:5])    # Hello
print(text[7:])     # from index 7 to the end
print(text[:5])     # from the start to index 5
print(text[-5:])    # last 5 characters
print(text[::2])    # every second character
print(text[::-1])   # reversedCode language: Python (python)

Output:

Hello
World
Hello
World
Hlo ol
dlroW ,olleH

Slicing never raises an IndexError, even if the indexes are out of range. Learn every slicing technique in String Slicing and Indexing in Python.

Strings are immutable

You can’t change a character in an existing string. Trying to assign to an index raises a TypeError:

word = "Python"
try:
    word[0] = "J"
except TypeError as error:
    print("Error:", error)Code language: Python (python)

Output:

Error: 'str' object does not support item assignment

Instead, build a new string and assign it to the variable:

word = "Python"
word = "J" + word[1:]
print(word)

greeting = "hello"
greeting.upper()          # returns a new string, but it isn't saved
print(greeting)
greeting = greeting.upper()
print(greeting)Code language: Python (python)

Output:

Jython
hello
HELLO

Immutability makes strings safe to use as dictionary keys and set items, and lets Python share identical strings in memory.

String operations

Concatenation and repetition

+ joins strings, and * repeats a string:

first = "Jessa"
last = "Doe"

full_name = first + " " + last
print(full_name)
print("ha" * 3)
print("=" * 30)Code language: Python (python)

Output:

Jessa Doe
hahaha
==============================

You can only concatenate strings with strings. "Age: " + 28 raises a TypeError. Use str(28) or an f-string instead.

Length, membership, and counting

message = "Python is fun and Python is powerful"

print(len(message))
print("fun" in message)
print("boring" not in message)
print(message.count("Python"))Code language: Python (python)

Output:

36
True
True
2

Comparing strings

Strings are compared character by character using Unicode code points. Uppercase letters (A is 65) come before lowercase letters (a is 97):

print("apple" == "apple")
print("apple" == "Apple")
print("apple" < "banana")
print("Zoo" < "apple")
print("apple".lower() == "APPLE".lower())  # case-insensitive
print("10" < "9")  # text comparison, not numericCode language: Python (python)

Output:

True
False
True
True
True
True

For case-insensitive comparisons of international text, use casefold() instead of lower().

Looping through a string

A string is iterable, so a for loop visits each character in order:

for ch in "Hi!":
    print(ch)

for index, ch in enumerate("abc"):
    print(index, ch)Code language: Python (python)

Output:

H
i
!
0 a
1 b
2 c

Example: count the vowels in a sentence

sentence = "Python strings are easy to learn"
vowels = sum(1 for ch in sentence.lower() if ch in "aeiou")
print(vowels)Code language: Python (python)

Output:

9

Common string methods

Strings have dozens of built-in methods. Here are the ones you’ll use daily:

text = "  Learn Python Programming  "

print(text.strip())            # remove surrounding spaces
print(text.lower())
print(text.upper())
print(text.strip().title())
print(text.replace("Python", "Java"))
print(text.find("Python"))     # index of first match, or -1
print(text.strip().startswith("Learn"))
print(text.strip().split())    # split into a list of wordsCode language: Python (python)

Output:

Learn Python Programming
  learn python programming  
  LEARN PYTHON PROGRAMMING  
Learn Python Programming
  Learn Java Programming  
8
True
['Learn', 'Python', 'Programming']

See Python String Methods for the full list with examples.

Splitting and joining strings

split() breaks a string into a list. join() does the opposite: it glues a list of strings together with a separator.

csv_line = "Jessa,28,London"
fields = csv_line.split(",")
print(fields)

words = ["Python", "is", "awesome"]
print(" ".join(words))
print("-".join(words))
print("".join(["a", "b", "c"]))Code language: Python (python)

Output:

['Jessa', '28', 'London']
Python is awesome
Python-is-awesome
abc

join() only accepts strings. Convert numbers first, for example ", ".join(map(str, [1, 2, 3])).

Formatting strings

Use f-strings to insert values into a string. Put f before the quotes and the values in braces:

name = "Kelly"
balance = 1520.5
print(f"{name} has ${balance:,.2f} in her account")
print(f"{name:>10}|")Code language: Python (python)

Output:

Kelly has $1,520.50 in her account
     Kelly|

Learn every formatting option in Python f-Strings and String Formatting.

Checking the content of a string

Methods that start with is return True or False:

print("12345".isdigit())
print("Python".isalpha())
print("Python3".isalnum())
print("   ".isspace())
print("hello".islower())
print("Hello World".istitle())Code language: Python (python)

Output:

True
True
True
True
True
True

Example: validate user input before converting it

for value in ["42", "4.2", "abc", "-7"]:
    if value.lstrip("-").isdigit():
        print(f"{value!r} -> {int(value)}")
    else:
        print(f"{value!r} is not a whole number")Code language: Python (python)

Output:

'42' -> 42
'4.2' is not a whole number
'abc' is not a whole number
'-7' -> -7

Unicode, encoding, and bytes

Python 3 strings are Unicode, so they can hold text in any language, plus symbols and emoji:

greetings = ["Hello", "Hola", "नमस्ते", "こんにちは", "Привет"]
for g in greetings:
    print(g, len(g))

print(ord("A"), chr(97))Code language: Python (python)

Output:

Hello 5
Hola 4
नमस्ते 6
こんにちは 5
Привет 6
65 a

len() counts Unicode code points, not visible letters. Some scripts, such as Hindi, combine several code points into one visible character, so len("नमस्ते") is 6.

To save text to a file or send it over a network, you encode it into bytes. To read it back, you decode the bytes into a string. UTF-8 is the standard encoding:

text = "café"
data = text.encode("utf-8")
print(data)
print(len(text), len(data))   # é takes 2 bytes in UTF-8
print(data.decode("utf-8"))Code language: Python (python)

Output:

b'caf\xc3\xa9'
4 5
café

Always pass encoding="utf-8" when opening text files, for example open("notes.txt", encoding="utf-8"), so your program behaves the same on every operating system.

Building strings efficiently

Because strings are immutable, += in a loop creates a new string every time. For many pieces, collect them in a list and join once:

# Slower for large loops
result = ""
for n in range(5):
    result += str(n)
print(result)

# Faster and cleaner
result = "".join(str(n) for n in range(5))
print(result)Code language: Python (python)

Output:

01234
01234

Useful constants in the string module

The string module provides ready-made sets of characters:

import string

print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.digits)
print(string.punctuation)Code language: Python (python)

Output:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
0123456789
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Example: remove punctuation from a sentence

import string

sentence = "Hello, World! Python's great."
clean = sentence.translate(str.maketrans("", "", string.punctuation))
print(clean)Code language: Python (python)

Output:

Hello World Pythons great

Common mistakes

  • Forgetting that strings are immutable. name.upper() doesn’t change name. Write name = name.upper().
  • Adding strings and numbers. "Total: " + 5 raises a TypeError. Use an f-string.
  • Off-by-one slicing. The stop index is excluded, so text[0:3] gives three characters.
  • Comparing numbers stored as text. "10" < "9" is True. Convert with int() first.
  • Using backslashes in Windows paths without a raw string. "C:\new" contains a newline. Use r"C:\new" or forward slashes.
  • Using is to compare strings. Always compare text with ==.

Practice exercises

Exercise 1: Check whether a word is a palindrome, ignoring case.

word = "Racecar"
print(word.lower() == word.lower()[::-1])Code language: Python (python)

Output:

True

Exercise 2: Print the initials of a full name in uppercase, such as J.K.R. for joanne kathleen rowling.

name = "joanne kathleen rowling"
initials = "".join(part[0].upper() + "." for part in name.split())
print(initials)Code language: Python (python)

Output:

J.K.R.

Exercise 3: Count how many times each character appears in a word.

word = "mississippi"
counts = {}
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)Code language: Python (python)

Output:

{'m': 1, 'i': 4, 's': 4, 'p': 2}

Summary

  • Create strings with single, double, or triple quotes. Use str() to convert other values.
  • Use escape sequences such as \n and \t for special characters, and raw strings (r"...") to keep backslashes as they are.
  • Access characters by index (s[0], s[-1]) and extract parts with slices (s[start:stop:step]).
  • Strings are immutable. Methods return new strings, so assign the result.
  • Join with +, repeat with *, check with in, split with split(), and combine with join().
  • Python strings are Unicode. Encode to bytes with encode() and decode with decode(), using UTF-8.

Also, See:

  • Python String Methods
  • String Slicing and Indexing in Python
  • Python f-Strings and String Formatting
  • Python String Exercises
  • Python String Quiz

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com