PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • πŸ§‘ People tracker
    • πŸš— Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. Python Basics
  2. Python: Strings
  • Python

  • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Exceptions
    • Python: Cheat-Sheets

On this page

  • 1 Overview
  • 2 Strings
  • 3 Strings in Python
  • 4 Escape sequences
  • 5 Raw strings
  • 6 Single or double quotes?
  • 7 Indexing
  • 8 Positive indexing
  • 9 Negative indexing
  • 10 Slicing
  • 11 Concatenation
  • 12 Repetition
  • 13 Comparison
  • 14 Methods
  • 15 Formatting
    • 15.1 %-formatting
    • 15.2 format() method
    • 15.3 F-strings
  • 16 Immutability
  • 17 Unicode
  • Edit this page
  • View source
  • Report an issue
  1. Python Basics
  2. Python: Strings

Python: Strings

Python Strings

python
strings
The file system is organized into a hierarchical structure, starting with the root directory
Author

Isaac Boixaderas

Published

Sunday, June 1, 2025

Modified

Sunday, November 16, 2025

1 Overview

πŸ“˜ Strings in Python

In Python, strings are used for representing textual data. A string is a sequence of characters enclosed in either single quotes (’’) or double quotes (β€œβ€). The Python language provides various built-in methods and functionalities to work with strings efficiently. Numbers tell computers how much or how many. Strings tell computers what β€” names, words, sentences, or any text. In other words, strings are how computers understand and manipulate tex


2 Strings

  • With strings, a computer can:

    • Say hello to someone.

    • Store a name.

    • Send a message.

    • Print a receipt.


3 Strings in Python

  • Sequence of characters enclosed in single, double or triple quotes.
string1 = 'Hello, World!'

string2 = "Hello, World!"

string3 = '''Multi-line
string 
example'''

string4 = """Multi-line 2
string 
example"""

  • Take care when mixing quotes!
failed_string = 'You're the best!'
SyntaxError: invalid syntax

failed_string = "and then she said: "I love this Python course!""
SyntaxError: invalid syntax

  • Properly mixing them:
successful_string = "You're the best!"
successful_string = 'she said: "I love this Python course!"'

4 Escape sequences

  • Include special characters in your strings by using backslash (\)

  • Common escape sequences: \', \", \\, \n, \t.

# Using a single quote inside a string enclosed in single quotes
print('You\'re the best!')
You’re the best!
# Using a double quote inside a string enclosed in double quotes
print("she said: \"I love this Python course!\"")
she said: β€œI love this Python course!”

# Use a double backslash to show a single backslash
print('C:\\Users\\Documents')
C:
# Use \n to enter a new line
print('Hello,\nWorld!')
Hello,
World!
# Use \t to add a tab
print('Hello,\tWorld!')
Hello, World!

5 Raw strings

  • Create string literals without processing escape sequences
  • Add r or R before the string.
  • Useful when working with paths, regular expressions, etc.
print(r'this string is \n not split.')
this string is not split.

–>

# Without a raw string
file_path = 'C:\\Users\\username\\Documents\\file.txt'
print(file_path)
# With a raw string
file_path = r'C:\Users\username\Documents\file.txt'
print(file_path)
C:.txt
C:.txt

–>


6 Single or double quotes?

  • No defined rules.

  • Some opinions:

    • Be consistent throughout your code, do not mix both types of quotes randomly, as this makes the code a bit more complex to read.

    • Do not use triple quotes if the string is not multi-line, as this makes the code a bit more complex to read.


7 Indexing

  • Access specific string characters by index.

String indexing in python

String indexing in python
From: https://www.codespeedy.com/

8 Positive indexing

  • Use [index number] after the string, indicating the index to access.
  • Zero-based.
greeting = 'Hello, World!'

print(greeting[0])  # Access the 1st character
print(greeting[2])  # Access the 3rd character
print(greeting[11]) # Access 12th character
H
l
d

9 Negative indexing

  • For accessing the elements of a string β€œbackwards”.

  • Use -1 for accessing the last element, -2 for the second to last, etc.

greeting = 'Hello, World!'

print(greeting[-1])  # Access the last character
print(greeting[-2])  # Access the second to last character
print(greeting[-12]) # Access the 12th character starting from the end
!
d
e

  • We get an error if we specify an index outside the range.
greeting = 'Hello, World!'

print(greeting[12])
β€˜!’
greeting[13]
IndexError: string index out of range
greeting[-15]
IndexError: string index out of range

10 Slicing

  • Extract a substring from a string.
  • Specify: start index, end index and step (optional).
    • substring = original_string[start:end:step]
  • Start is included.
  • End is not included.
  • Step defaults to 1 if not provided.
  • Start and end default to 0 if not provided.

greeting = 'Hello, World!'

# Extract the substring from index 0 to 4 (inclusive)
print(greeting[0:5])
Hello

# Extract the first four characters
print(greeting[:4])
Hell

# Extract the last three characters
print(greeting[-3:])
ld!

greeting = 'Hello, World!'

# Extract characters with a step of 2
print(greeting[::2])
Hlo ol!

# Extract the substring from index 1 to 6 with a step of 2
print(greeting[1:6:2])
el,

# Trick for reversing a string
print(greeting[::-1])
!dlroW ,olleH

11 Concatenation

  • With + operator:
full_name = 'John' + ' ' + 'Doe'
print(full_name)
John Doe

12 Repetition

  • With * operator:
laugh = 'Ha' * 3
print(laugh)

laugh = 'Ha' * 10
print(laugh)
HaHaHa
HaHaHaHaHaHaHaHaHaHa

13 Comparison

  • Standard comparison operators: ==, <, >=, etc.
  • Comparison performed based on the Unicode code point (ordinal) value of each character. It is similar to the way words are sorted in a dictionary.
print('a' < 'b')
print('a' < 'A')
print('a' < 'aa')
print('abc' == 'abc')
True
False
True
True

14 Methods

  • Python provides a variety of functions, string methods, and keywords to make string manipulation easier.

  • Built-in functions:

    • len(): Function that returns the length of the string.
greeting = 'Hello, World!'

print(len(greeting))
13

  • String methods:
    • upper(): Converts the string to uppercase.
    • lower(): Converts the string to lowercase.
greeting = 'Hello, World!'

print(greeting.lower())
hello, world!
print(greeting.upper())
HELLO, WORLD!

  • find(): Returns the index of the first occurrence of a substring.
greeting = 'Hello, World!'

print(greeting.find('Wo'))
7

  • replace(): Replaces a substring with another substring.
greeting = 'Hello, World!'

print(greeting.replace('World', 'Universe'))
Hello, Universe!

  • Trick to remove part of a string:
greeting = 'Hello, World!'

print(greeting.replace(', World', ''))
Hello!

  • Keywords:
    • in: Checks if a specified substring is present within a given string. It returns True if the substring is found, and False otherwise.
    • not in: Checks if a substring is not present in a given string.
greeting = 'Hello, World!'

print('Hello' in greeting)
True
print('Hello' not in greeting)
False

15 Formatting

  • Process of creating a new string by combining text with variables.
  • Several methods:
    • %-formatting.
    • .format() method.
    • f-strings.

15.1 %-formatting

  • Old-style formatting.
  • Use % inside the string with element specifier.
  • Use % after the string for adding the variables.
  • See specifiers at: https://docs.python.org/3/library/stdtypes.html#old-string-formatting
name = 'John'
age = 30
formatted = 'My name is %s, and I am %i years old.' % (name, age)

print(formatted)
My name is John, and I am 30 years old.

15.2 format() method

  • New-style formatting.
  • String method.
  • Use curly braces {} in text as placeholders for variables.
  • Specify variables as format() arguments.
name = 'John'
age = 30
formatted = 'My name is {}, and I am {} years old.'.format(name, age)

print(formatted)
My name is John, and I am 30 years old.

15.3 F-strings

  • Most recent.
  • Recommended.
  • Add f before the string.
  • Add variables inside text enclosed with curly braces {}.
name = 'John'
age = 30
formatted = f'My name is {name}, and I am {age} years old.'

print(formatted)
My name is John, and I am 30 years old.

  • F-strings allow nice options for formatting.
  • For example, rounding to a specific number of decimals by including :.Xf
print(f'One divided by six is {1 / 6}')
print(f'One divided by six rounded {1 / 6:.0f}')
print(f'One divided by six with 1 decimal {1 / 6:.1f}')
print(f'One divided by six with 2 decimals is {1 / 6:.2f}')
One divided by six is 0.16666666666666666
One divided by six rounded 0
One divided by six with 1 decimal 0.2
One divided by six with 2 decimals is 0.17

  • Or displaying a large integer number separating the thousands with commas to make it more readable:
big_number = 1000000

print(f'Big number difficult to visualize: {big_number}')
print(f'Big number easy to visualize: {big_number:,}')
Big number difficult to visualize: 1000000
Big number easy to visualize: 1,000,000
  • You can find some more formatting examples here: https://www.pythonmorsels.com/string-formatting/

16 Immutability

  • In Python, strings are immutable.
  • Original string is never modified.
  • For changing a string, we have to create a new one.
  • It is forbidden to change strings using indexing:
original_string = 'Hello, World!'

# Strings are immutable,
# trying to change 'H' for 'J' results in an error
original_string[0] = 'J'
TypeError: β€˜str’ object does not support item assignment

  • We should create a new string variable with the desired changes.
  • For example, using slicing and concatenation:
original_string = 'Hello, World!'

# Changing 'H' for 'J'
new_string = 'J' + original_string[1:]

print(new_string)
Jello, World!

  • Another common option is to use the replace() method:
modified_string = original_string.replace('World', 'Python')

print(original_string)  # has not changed
print(modified_string)
Hello, World!
Hello, Python!

  • If the value returned by a method is not assigned to a variable, the result is lost:
original_string = 'Hello, World!'
# The resulting string is not assigned to a variable nor printed
original_string.replace('World', 'Python')

print(original_string)
Hello, World!

17 Unicode

  • Standard for representing characters from all languages.
  • Python strings support Unicode by default.
  • UTF-8 is the most common Unicode encoding for Python strings.
japanese_greeting = "こんにけは"  # Japanese
korean_greeting = "μ•ˆλ…•ν•˜μ„Έμš”"  # Korean
Back to top
Python: Numbers
Python: Conditionals

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue