Home ยป Python Strings Tutorial

Python Strings Tutorial

Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification

In Python, strings are sequences of characters enclosed in either single quotes (‘) or double quotes (“).

Strings are one of the most widely used data types, and Python provides many useful operations and methods to manipulate them.

In this tutorial, we will explore the basics of working with strings in Python, including creating strings, accessing and slicing them, using common string methods, formatting strings, and more.

We will cover each topic with practical examples.

1. Creating Strings

Strings in Python can be created by enclosing characters in either single, double, or triple quotes. Triple quotes are commonly used for multi-line strings.

Example: Creating Strings

# Example: Creating strings
single_quote_string = 'Hello, World!'
double_quote_string = "Python Strings"
multi_line_string = """This is a
multi-line string in Python."""

print(single_quote_string)  # Output: Hello, World!
print(double_quote_string)  # Output: Python Strings
print(multi_line_string)
# Output:
# This is a
# multi-line string in Python.

In this example:

Single quotes and double quotes can be used interchangeably to create strings.
Triple quotes (”' or “””) are used for multi-line strings.

2. Accessing Characters in a String

Strings in Python are indexed, meaning each character has a position (starting from 0). You can access individual characters using indexing and extract parts of the string using slicing.

Example: Indexing and Slicing Strings

# Example: Accessing characters in a string
text = "Python"

# Access individual characters
print(text[0])  # Output: P
print(text[1])  # Output: y

# Negative indexing (from the end)
print(text[-1])  # Output: n
print(text[-2])  # Output: o

# Slicing (substring)
print(text[0:3])  # Output: Pyt (characters from index 0 to 2)
print(text[2:])   # Output: thon (from index 2 to the end)
print(text[:4])   # Output: Pyth (up to index 3)

In this example:

Indexing allows you to access individual characters in the string. Negative indexing starts from the end of the string.
Slicing is used to extract a substring by specifying the start and end positions. The end index is exclusive.

3. String Concatenation and Repetition

You can concatenate (join) two or more strings using the + operator and repeat strings using the * operator.

Example: Concatenating and Repeating Strings

# Example: Concatenating and repeating strings
str1 = "Hello"
str2 = "World"

# Concatenation
concatenated_str = str1 + ", " + str2 + "!"
print(concatenated_str)  # Output: Hello, World!

# Repetition
repeated_str = "Python " * 3
print(repeated_str)  # Output: Python Python Python

In this example:

The + operator is used to concatenate strings.
The * operator repeats the string multiple times.

4. Common String Methods

Python provides a wide range of built-in methods to manipulate strings. Some of the most commonly used methods include:

lower(): Converts a string to lowercase.
upper(): Converts a string to uppercase.
strip(): Removes leading and trailing spaces.
replace(): Replaces a substring with another substring.
find(): Finds the position of a substring.
split(): Splits a string into a list of substrings.

Example: Using Common String Methods

# Example: Common string methods
text = "  Python Programming  "

# Convert to lowercase
print(text.lower())  # Output: "  python programming  "

# Convert to uppercase
print(text.upper())  # Output: "  PYTHON PROGRAMMING  "

# Remove leading and trailing spaces
print(text.strip())  # Output: "Python Programming"

# Replace a substring
print(text.replace("Python", "Java"))  # Output: "  Java Programming  "

# Find the position of a substring
print(text.find("Programming"))  # Output: 9 (starting index of "Programming")

# Split the string into a list of words
words = text.split()
print(words)  # Output: ['Python', 'Programming']

In this example:

We use various string methods to manipulate the string: converting to lowercase/uppercase, removing spaces, replacing substrings, finding substrings, and splitting the string.

5. String Formatting

String formatting allows you to insert values into a string dynamically. Python offers several ways to format strings, including f-strings (available in Python 3.6 and above), format(), and the % operator (old-style).

Example: String Formatting Using f-strings

# Example: String formatting using f-strings (Python 3.6+)
name = "Alice"
age = 30
profession = "Engineer"

# Using f-strings to format the string
formatted_str = f"My name is {name}, I'm {age} years old, and I'm an {profession}."
print(formatted_str)
# Output: My name is Alice, I'm 30 years old, and I'm an Engineer.

Example: String Formatting Using format()

# Example: String formatting using format()
name = "Bob"
age = 25

# Using the format() method
formatted_str = "My name is {}, and I am {} years old.".format(name, age)
print(formatted_str)
# Output: My name is Bob, and I am 25 years old.

In these examples:

f-strings (formatted string literals) allow you to embed expressions inside curly braces {}.
The format() method inserts values into placeholders {} in the string.

6. Checking for Substrings

You can check whether a substring exists within a string using the in operator or not in operator.

Example: Checking for Substrings

# Example: Checking for substrings
text = "Python is fun"

# Check if "Python" is in the string
print("Python" in text)  # Output: True

# Check if "Java" is not in the string
print("Java" not in text)  # Output: True

In this example:

The in operator checks if a substring is present in the string.
The not in operator checks if a substring is absent.

7. Joining Strings

The join() method is used to join elements of a list or iterable into a single string with a specified delimiter.

Example: Joining Strings

# Example: Joining strings
words = ["Python", "is", "fun"]

# Join the list of words with a space
sentence = " ".join(words)
print(sentence)  # Output: Python is fun

# Join the list of words with a hyphen
hyphenated_sentence = "-".join(words)
print(hyphenated_sentence)  # Output: Python-is-fun

In this example:

join() is used to concatenate a list of words into a single string, with a specified separator (space or hyphen).

8. String Immutability

Strings in Python are immutable, meaning once a string is created, it cannot be changed. Any operation that seems to modify a string will create a new string instead of modifying the original one.

Example: String Immutability

# Example: String immutability
text = "Hello"

# Trying to modify a character (this will raise an error)
# text[0] = "h"  # Uncommenting this line will raise a TypeError

# Creating a new string instead
new_text = "h" + text[1:]
print(new_text)  # Output: hello

In this example:

Strings are immutable, so attempting to modify them directly will raise a TypeError. To change a string, you need to create a new string.

9. Escaping Characters

If you want to include special characters like quotes or newlines inside a string, you can use escape sequences. Escape sequences start with a backslash (\).

Example: Escaping Characters

# Example: Escaping characters
text_with_quotes = "He said, \"Python is great!\""
new_line_string = "First line\nSecond line"

print(text_with_quotes)  # Output: He said, "Python is great!"
print(new_line_string)
# Output:
# First line
# Second line

In this example:

\” is used to include double quotes inside a string.
\n is used to insert a newline character.

10. String Length and Iteration

You can find the length of a string using the len() function and iterate through the characters of a string using loops.

Example: Finding String Length and Iterating

# Example: Finding length and iterating over a string
text = "Python"

# Get the length of the string
print(len(text))  # Output: 6

# Iterate through each character in the string
for char in text:
    print(char)

# Output:
# P
# y
# t
# h
# o
# n

In this example:

len() returns the number of characters in the string.
A for loop is used to iterate through each character in the string.

Summary

Python strings are sequences of characters enclosed in single, double, or triple quotes. They are immutable, meaning they cannot be modified after creation.
You can perform various operations on strings, such as concatenation, slicing, and repetition.
Python provides many string methods to manipulate and process strings, such as lower(), upper(), replace(), find(), and split().
String formatting allows you to dynamically insert values into strings using f-strings or the format() method.
Strings can be checked for substrings using the in and not in operators, and joined using the join() method.
Escape characters allow you to include special characters like quotes or newlines in a string.

By mastering string operations in Python, you can handle text processing tasks efficiently and write more effective code.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More