Python String Explain with Examples

Python string is a fundamental data type that is used to represent and manipulate text, numbers, and special characters. In this article, we’ll explore the basics of strings in Python and show you how to use them with examples.

Python strings are immutable, meaning that once they are created, they cannot be changed. This can be seen as an advantage because it makes strings more secure and predictable in terms of their behavior.

1. What is String in Python?

A string in Python is a data type and data structure that is used to store sequences of characters and manipulate text-based data. They are represented by a set of characters enclosed in quotes, either single or double.

Python String datatype support indexing, which allows you to access individual characters within a string. This can be useful for tasks such as parsing and extracting information from strings.

Note that Python does not have a character data type, so to represent a single character use a character within single or double quotes. In other words, the character is simply a string with a length of 1.

You can access the character from a String by using square brackets.

1.1 Example of String in Python

Following are some quick examples of defining strings.

# String with double quote
greeting = "Good morning!"

# String with single quote
my_string = 'This is a string'

1.2 Key Points about String

Key PointDescription
Enclosed in quotesStrings are enclosed in single or double quotes
ConcatenationUse the + operator to combine strings
RepetitionUse the * operator to repeat a string
IndexingAccess individual characters in a string by index, starting from 0
SlicingUse a colon : to access a range of characters in a string
len() functionDetermine the length of a string
Escape charactersUse the backslash () to include special characters in a string
Raw stringsUse ‘r’ prefix to create raw strings, ignore escape characters
String methodsManipulate strings using various built-in methods
String formattingUse format() or f-strings to insert values into strings
Important Points about Python String

2. Create a String in Python

Python allows you to create strings in a variety of ways. There are two primary methods for creating strings: using the str() function and using single, double, or triple quotes.

2.1 Using single, double, or triple quotes

In Python, you can create strings using single quotes (‘), double quotes (“) or triple quotes (”’ or “””). The primary difference between single quotes and double quotes is that you can use single quotes within a string created with double quotes, and vice versa. However, you cannot nest quotes of the same type within each other.

# Create a string using single quotes
string = 'I love SparkByExample.Com'

# Output: 
# 'I love SparkByExample.Com'

# Create a string using double quotes
string = "I love 'SparkByExample.Com'"
# Output: 
# "I love 'SparkByExample.Com'"

Triple quotes, on the other hand, allow you to create multi-line strings. You can use either single quotes (”’) or double quotes (“””). This can be useful when you need to include line breaks within your string.

# Create a multi-line string using triple quotes
string = """I love,

# Output: 
# 'I love,\nSparkByExampls!,\nWorld!'

2.2 Using the str() function

The str() function is a built-in function in Python that allows you to convert any data type into a string. It takes any object as an argument and returns a string representation of that object. The returned string can be used for display purposes or can be stored in a string variable.

# Create a string from a number
number = 502
string = str(number)

# Output: 
# '502'

# Create a string from a list
list = [1, 2, 3]
string = str(list)

# Output: 
# '[1, 2, 3]'

3. Access Characters in a String

Strings are sequences of characters, which means that they can be accessed and manipulated like any other sequence data type (such as lists, sets, or tuples). To access individual characters in a string, you can use indexing and slicing.

string = "Spark By Examples"

# Access the first character
first_char = string[0]

# Output: 'S'

# Access the last character
last_char = string[-1]

# Output: 's'

# Access a sub-string (slicing)
sub_string = string[4:9]

# Output: 'By E'

Negative indexing in Python allows you to access characters in a string starting from the end of the string, rather than from the beginning. With negative indexing, the last character of a string is at index -1, the second-to-last character is at index -2, and so on.

4. Types of Python String

There are several types of strings that serve different purposes, including Formatted Strings, Raw Strings, Byte Strings, and Doc Strings. Each of these string types has unique properties and use cases, making it important to understand the differences between them.

4.1 Formatted String

Formatted strings in Python are created using the format() method, which allows you to substitute values into a string. Formatted strings are useful for creating dynamically generated strings with values that may change at runtime.

site= "SparkByExamples"
time= 5

# Create a formatted string
formatted_string = "I visit {} for {} hours.".format(site, time)

# Output: 
# 'I visit SparkByExamples for 5 hours.'

The f-string, or f-formatted string, is a newer and more concise way of formatting strings in Python.

name = ""
f_string = f"I love {name}"

# Output: 
# I love

4.2 Raw String

Raw strings in Python are created by prefixing a string literal with the letter r. Raw strings are useful for representing regular expressions or Windows file paths, whereas backslashes are used as escape characters.

# Create a raw string
raw_string = r"C:\Users\Spark\Desktop"

# Output: 
# 'C:\\Users\\Spark\\Desktop'

4.3 Byte String

A byte string is a sequence of bytes and each byte can take any value between 0 and 255, representing an 8-bit number. In Python 3, byte strings are different from regular strings, which are Unicode strings.

This means that the operations and methods available for byte strings are different from those available for regular strings.

# Create a byte string
byte_string = b"Spark By Examples"

# Output: 
# b'Spark By Examples'

It’s important to use byte strings instead of regular strings when working with binary data because regular strings use Unicode encoding, which may not be suitable for all binary data.

Below are the use cases of Byte String in Python:

  1. Byte strings are used to store binary data such as image, audio, and video files.
  2. Byte strings are often used when sending or receiving data over a network, as they can represent the raw binary data being transmitted.
  3. Byte strings can be used when reading and writing binary files, such as images, audio, or video files.
  4. Byte strings can be used to encode and decode data in various formats, such as base64 or hexadecimal.

4.4 doc String

A docstring is a special type of string in Python that provides documentation for a Python module, function, class, or method. A docstring is surrounded by triple quotes (either single quotes or double quotes).

It is placed immediately after the definition of the module, function, class, or method and is used by the help() function to provide information about the object.

def multiply(a, b):
    This function returns the product of two numbers.
        a (int): The first number.
        b (int): The second number.
        int: The product of a and b.
    return a * b

You can access the docstring of a Python object using the help() function. For example:

>>> help(multiply)

5. Splitting a String

You can split a string into multiple substrings using the split() method. This method splits a string into a list of substrings based on a specified separator. If the separator is not specified, the string is split on whitespace characters.

example_string = "SparkByExamples"
result = example_string.split()

# Output: 
# ['SparkByExamples']

result = example_string.split("k")

# Output: 
# ['Spar', 'ByExamples']

6. Joining a String

Joining refers to the process of combining a series of strings into a single string. The process of joining strings is also called “concatenation”.

The resulting string can be separated by a specified delimiter, such as a space, a comma, or a custom string. See the following examples.

example_list = ['Spar', 'ByExamples']
result = "k".join(example_list)

# Output: 
# 'SparkByExamples'

7. String Slicing

String slicing allows you to extract a portion of a string and return it as a new string. The slice includes all characters between the start and end indices.

# Get a sub-string from index 0 to 5
result = example_string[0:5]

# Output: 
# 'Spark'

# Get a sub-string from index 5 to the end of the string
result = example_string[5:]

# Output: 
# 'ByExamples'

# Get a sub-string from the start of the string to index 5 
result = example_string[:5]

# Output:
# 'Spark'


We discussed Python String and how to create, manipulate, and access strings in Python. You now have a clear understanding of the basics of working with strings in Python. Comment below if you have any questions.

Happy Learning!!!


I am an astute software engineer with extensive 3+ years of experience in developing full-stack web applications. My skillets include building backend services for different databases. Mainly I work with Python, Flask, Django, and FastAPIs. Being Python Specialist, I have worked with Numpy, Pandas, and other Python Libraries to build tools that make ETL normalization easier.

Leave a Reply

You are currently viewing Python String Explain with Examples