Skip to main content
Back

Programming with Strings in Python: Concepts, Indexing, Slicing, and Methods

Study Guide - Smart Notes

Tailored notes based on your materials, expanded with key definitions, examples, and context.

Programming with Strings

Introduction

Strings are one of the most fundamental data types in Python, used to represent sequences of characters. Understanding how to manipulate and process strings is essential for programming in Python, as strings are used for text processing, data input/output, and more.

String Literals

Definition and Usage

  • String literal: A sequence of characters treated as a single item in Python.

  • Characters in strings can include letters, numbers, symbols, spaces, and special characters.

  • String literals are written by enclosing characters in single quotes (') or double quotes (").

  • Opening and closing quotation marks must be of the same type.

Examples:

  • 'John Doe'

  • "123 5th Avenue"

  • 'Say it ain\'t so, Joe!'

String Variables

Assigning and Displaying Strings

  • Variables can be assigned string values, which can then be used in expressions or displayed with print().

  • Quotation marks are not included in the output when printing string variables.

Examples:

  • greeting = "Peace for Everyone"

  • snack = "cookies and milk"

String Concatenation

Combining Strings

  • Strings can be combined (concatenated) using the plus sign (+).

  • Concatenation creates a new string from the operands.

Example:

  • "good" + "bye" results in "goodbye"

String Repetition

Repeating Strings

  • The asterisk operator (*) can be used to repeat a string n times: string * n.

Expression

Value

"ha" * 4

"hahahaha"

"mur" * 2

"murmur"

"x" * 10

"xxxxxxxxxx"

("cha" * 2) + "cha"

"cha-cha-cha"

Indices and Slices

Accessing Characters and Substrings

  • Each character in a string has an index, starting from 0 for the first character.

  • Use len(string) to find the length of a string.

  • Access a single character with string[index].

Example:

  • For str1 = "cookies & milk":

  • len(str1) returns 14

  • str1[4] returns "i"

Slicing Strings

  • A slice extracts a substring: string[m:n] returns the substring from index m up to, but not including, n.

  • If m and n are equal, or if m > n, the result is an empty string "".

Example:

  • "cookies & milk"[2:7] returns "okies"

  • str1[5:2] returns ""

Negative Indices

  • Negative indices count from the end of the string: -1 is the last character, -2 is the second-to-last, etc.

Example:

  • For str1 = "cookies & milk", str1[-1] is "k"

Default Bounds for Slices

  • If the left bound is omitted, it defaults to 0.

  • If the right bound is omitted, it defaults to the length of the string.

  • str1[:n] is the substring from the start up to (but not including) n.

  • str1[m:] is the substring from m to the end.

  • str1[:] is the entire string.

Examples:

  • "Python"[2:] returns "thon"

  • "Python"[:4] returns "Pyth"

  • "Python"[:] returns "Python"

  • "Python"[-3:] returns "hon"

  • "Python"[:-3] returns "Pyt"

Indexing and Slicing Out of Bounds

  • Indexing a character out of bounds (e.g., str1[100]) raises an IndexError.

  • Slicing with out-of-bounds indices does not raise an error; Python adjusts the bounds as needed.

Examples:

  • str1[-10:10] returns the string up to index 10.

  • str1[2:10] returns the substring from index 2 to 9.

String Functions and Methods

Overview

  • A string function takes a string as input and returns a value.

  • A string method is a function that is called on a string object using dot notation: stringName.methodName().

  • Method names are case-sensitive.

Common String Methods

Method

Description

Example

Result

upper()

Converts all characters to uppercase

"python".upper()

"PYTHON"

lower()

Converts all characters to lowercase

"Python".lower()

"python"

count(sub)

Counts non-overlapping occurrences of sub

"banana".count("a")

3

capitalize()

Capitalizes the first character

"hello".capitalize()

"Hello"

title()

Capitalizes the first character of each word

"hello world".title()

"Hello World"

rstrip()

Removes whitespace from the right side

"hello ".rstrip()

"hello"

Finding Substrings

  • find(subStr): Returns the index of the first occurrence of subStr (or -1 if not found).

  • rfind(subStr): Returns the index of the last occurrence of subStr (or -1 if not found).

Examples:

  • "cookies & milk".find("o") returns 1

  • "cookies & milk".rfind("o") returns 2

  • "Computer".find("x") returns -1

Chained Methods

  • Methods can be chained together: string.method1().method2().

  • Chaining is executed from left to right.

  • For readability, avoid chaining more than two methods together.

Example:

  • "Good Doggie".upper().count('G') returns 3

The input() Function

Getting User Input

  • input(prompt) displays a prompt and waits for the user to enter data.

  • The user's input is always returned as a string.

  • Assign the result to a variable for further processing.

Example:

  • city = input("Enter the name of your city: ")

Processing User Input

  • To convert input to a number, use int() for integers or float() for floating-point numbers.

  • eval() can also be used to evaluate numeric expressions, but int() and float() are preferred for safety and speed.

Examples:

  • age = int(input("Enter your age: "))

  • price = float(input("Enter the price: "))

Type Conversion Functions

Converting Between Strings and Numbers

  • int(string): Converts a string containing a whole number to an integer.

  • float(string): Converts a string containing a decimal number to a float.

  • str(number): Converts a number to its string representation.

Function

Example

Result

int()

int("4.8")

Error (cannot convert float string directly)

float()

float("4.67")

4.67

int()

int(4.8)

4

float()

float(-4)

-4.0

Note: Strings cannot be concatenated with numbers directly. Use str() to convert numbers to strings before concatenation.

Example:

  • print("python" + str(3)) outputs "python3"

Immutability of Strings

Strings Cannot Be Changed In Place

  • Individual characters in a string cannot be changed by assignment.

  • To modify a string, create a new string using concatenation or slicing.

Example:

  • The following code raises an error: word = "resort" word[2] = 'p'

Summary Table: String Indexing and Slicing

Operation

Description

Example

Result

string[index]

Access character at position index

"Python"[1]

"y"

string[m:n]

Substring from m to n-1

"Python"[2:4]

"th"

string[-1]

Last character

"Python"[-1]

"n"

string[:n]

From start to n-1

"Python"[:4]

"Pyth"

string[m:]

From m to end

"Python"[2:]

"thon"

Additional info:

  • Strings are of type str in Python.

  • Use print(dir(str)) to see all available string methods (ignore those starting and ending with double underscores).

  • Each character in a string has both a positive and a negative index.

Pearson Logo

Study Prep