Skip to main content

Introduction to Python Strings

Python Strings

A string is a sequence of characters enclosed in single quotes (') or double quotes (").

Strings are one of the fundamental data types in Python and are used to represent textual data.

Here are some examples of strings:

name = 'Alice'
message = "Hello, World!"
address = "123 Main Street"

Strings in Python are immutable, meaning that once created, they cannot be modified. However, you can perform various operations and manipulations on strings using built-in string methods and operators.

Here are some common operations and examples:

  • String Concatenation: You can concatenate two or more strings together using the + operator.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: "John Doe"
  • String Length: You can obtain the length of a string using the len() function.
message = "Hello, World!"
length = len(message)
print(length) # Output: 13
  • String Indexing: You can access individual characters in a string using indexing, where the first character has an index of 0.
message = "Hello"
print(message[0]) # Output: "H"
print(message[3]) # Output: "l"
  • String Slicing: You can extract a portion of a string using slicing, which allows you to specify a range of indices.
message = "Hello, World!"
print(message[0:5]) # Output: "Hello"
print(message[7:]) # Output: "World!"
  • String Methods: Python provides a variety of built-in string methods for manipulating and working with strings.

Some common methods include upper(), lower(), strip(), split(), replace(), and more.

Here are a few examples:

message = "Hello, World!"

print(message.upper()) # Output: "HELLO, WORLD!"
print(message.lower()) # Output: "hello, world!"
print(message.strip()) # Output: "Hello, World!" (removes leading/trailing whitespace)
print(message.split(",")) # Output: ["Hello", " World!"] (splits the string at commas)
print(message.replace("Hello", "Hi")) # Output: "Hi, World!" (replaces "Hello" with "Hi")
  • String Formatting: Python provides multiple ways to format strings, allowing you to combine variables or values within a string. Some common formatting methods include f-strings, str.format(), and % operator.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
print("My name is {} and I am {} years old.".format(name, age))
print("My name is %s and I am %d years old." % (name, age))

String Methods for Manipulation: Python offers a variety of string methods for manipulating and modifying strings. Some examples include startswith(), endswith(), count(), find(), isalpha(), isdigit(), join(), and more.

message = "Hello, World!"

print(message.startswith("Hello")) # Output: True
print(message.endswith("World!")) # Output: True
print(message.count("l")) # Output: 3 (counts the occurrences of "l" in the string)
print(message.find("World")) # Output: 7 (returns the index of the first occurrence of "World")
print(message.isalpha()) # Output: False (checks if the string consists of alphabetic characters)
print(message.isdigit()) # Output: False (checks if the string consists of digits)

String Escaping: If you need to include special characters within a string, you can use escape sequences. Common escape sequences include \n for a new line, \t for a tab, \" for a double quote, and \' for a single quote.

message = "Hello\nWorld!"
print(message) # Output:
# Hello
# World!

quote = "He said, \"Hello!\""
print(quote) # Output: He said, "Hello!"

String Concatenation with Join: If you have a list of strings that you want to concatenate, you can use the join() method to join them with a specific delimiter.

fruits = ["apple", "banana", "orange"]
combined_fruits = ", ".join(fruits)
print(combined_fruits) # Output: "apple, banana, orange"