You are currently viewing 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.

Advertisements

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!"
print(greeting)

# String with single quote
my_string = 'This is a string'
print(my_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'
print(string) 

# Output: 
# 'I love SparkByExample.Com'

# Create a string using double quotes
string = "I love 'SparkByExample.Com'"
print(string)
 
# 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,
SparkByExampls!"""
print(string) 

# 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)
print(string) 

# Output: 
# '502'

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

# 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]
print(first_char) 

# Output: 'S'

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

# Output: 's'

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

# 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)
print(formatted_string) 

# 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 = "SparkByExample.com"
f_string = f"I love {name}"
print(f_string)

# Output: 
# I love SparkByExample.com

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"
print(raw_string) 

# 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"
print(byte_string) 

# 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.
    
    Parameters:
        a (int): The first number.
        b (int): The second number.
    
    Returns:
        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()
print(result)

# Output: 
# ['SparkByExamples']

result = example_string.split("k")
print(result)

# 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)
print(result)

# 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]
print(result)

# Output: 
# 'Spark'

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

# Output: 
# 'ByExamples'

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

# Output:
# 'Spark'

Conclusion

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!!!