Python String

This Page contains everything about Python String. We will discuss what a string is in Python, and various Python string methods with examples. We will also check out, various string operations that we can do in Python.

What is a Python String?

A string in Python is a sequence of characters enclosed within single quotes (”), double quotes (“”), or triple quotes (”’ or “””). They are one of the most commonly used data types and play a pivotal role in handling textual information. In Python, strings are immutable, meaning that once created, their content cannot be changed directly. Instead, operations on strings create new strings as output.

Create a string in Python

In Python, you can create strings by enclosing your desired text in either single or double quotes. Triple quotes are typically used for multi-line strings.

single_quote_string = 'Hello, Python!'
double_quote_string = "Hello, Python!"
triple_quote_string = '''This is a
multi-line string in

Basic Python String Operations

Now, let us check out a few basic python string operations.

Concatenation: Joining two or more strings is easy using the + operator.

first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name)  # Output: Ada Lovelace

Repetition: You can repeat a string by using the * operator with an integer.

repeat_string = "Python! " * 3
print(repeat_string)  # Output: Python! Python! Python! 

Indexing: You can access individual characters in a string using their index.

sample_string = "Python"
print(sample_string[0])  # Output: P

Slicing: You can extract a substring by specifying the start and end indices.

sample_string = "Python"
print(sample_string[1:4])  # Output: yth

Various String Methods in Python

Python offers numerous built-in methods to manipulate strings. Some popular string methods include:

  1. upper(): Converts all characters in the string to uppercase.
  2. lower(): Converts all characters in the string to lowercase.
  3. strip(): Removes any leading and trailing whitespaces from the string.
  4. replace(old, new): Replaces all occurrences of the ‘old’ substring with the ‘new’ substring.
  5. split(separator): Splits the string into a list of substrings based on the specified separator.
  6. Python String replace(): How to use Python replace() method with examples.
  7. Python String format(): This tutorial explains about string format() method in Python.
  8. Python string uppercase(): This article explains the Python string uppercase() method.

Python String Tutorials

Here are a few detailed tutorials on Python strings.

This article has provided an overview of Python strings, including their creation, basic operations, string methods, and formatting techniques.