Search⌘ K
AI Features

Strings and String Methods

Explore how to define strings, access characters with indexing and slicing, and use built-in methods like strip, upper, and replace to transform text. Learn to format strings with f-strings, enabling dynamic and clear output in Python.

Text is the primary medium through which software interacts with humans. Whether we are processing user input, reading files, or generating reports, our programs constantly read, modify, and display text. Python is renowned for handling text efficiently, enabling us to perform complex transformations, such as data cleaning or formatting dynamic messages, with clear, readable syntax. In this lesson, we will master the tools needed to construct strings, extract specific data from them, and transform them to suit our application's logic.

Creating string literals

We define strings in Python by enclosing text in either single quotes (') or double quotes ("). Python treats both identically, but having two options gives us flexibility. If our text contains a single quote (like an apostrophe), we can wrap it in double quotes to avoid a syntax error, and vice versa.

Python 3.14.0
# Using single and double quotes
greeting = "Hello, Developer"
alert = 'System status: "Critical"'
contraction = "It's a great day to code"
print(greeting)
print(alert)
print(contraction)
  • Line 2: We define a standard string using double quotes, which is the most common way to represent text in Python.

  • Line 3: We leverage quote nesting by using single quotes on the outside. This tells Python that any double quotes found inside the string should be treated as literal text (part of the message) rather than the end of the code instruction.

  • Line 4: We reverse the strategy to handle a contraction. By using double quotes for the variable, we can safely include a single quote (an apostrophe) without the interpreter mistakenly thinking the string has closed early.

  • Lines 6–8: We output the variables to confirm that Python has correctly preserved the internal punctuation while successfully identifying the boundaries of each text block.

Concatenation: Joining strings

We often need to combine small pieces of text into a larger message. We call this concatenation, and in Python, we perform it using the + operator.

Python 3.14.0
first_name = "Ada"
last_name = "Lovelace"
# Concatenating strings
full_name = first_name + " " + last_name
print(full_name)
  • Line 5: ...