😨Strings

In Python, a string is a sequence of characters, which can be either letters, numbers, or symbols, enclosed within single quotes (' '), double quotes (" "), or triple quotes (""" """ or ''' '''). Strings are one of the most commonly used data types in Python, and they are immutable, which means that once a string is created, it cannot be modified.

Python provides a range of built-in functions and methods to manipulate strings, including slicing, concatenation, repetition, and searching. Understanding how to work with strings is essential in Python programming, as strings are often used to store and manipulate textual data such as user inputs, file names, and messages.

Creating a String

In Python, you can create a string by enclosing a sequence of characters in either single quotes ('...') or double quotes ("..."). Here's an example:

# creating a string using single quotes
my_string = 'Hello, World!'
print(my_string)

# creating a string using double quotes
my_string2 = "Hello, Python!"
print(my_string2)

Output:

Hello, World!
Hello, Python!

You can also create a string using triple quotes ('''...''' or """..."""). Triple-quoted strings can span multiple lines and are often used for docstrings or for multi-line strings. Here's an example:

# creating a string using triple quotes
my_string3 = '''This is a
multi-line string
using triple quotes.'''
print(my_string3)

Output:

This is a
multi-line string
using triple quotes.

Accessing Characters in a String

We can access the characters in a string in three ways.

  1. Indexing

Indexing is used to access a specific character in a string by referring to its position using an index number enclosed in square brackets []. The index number starts from 0 for the first character in the string and increases by 1 for each subsequent character.

Here is an example of indexing a string:

my_string = "Hello, World!"
print(my_string[0])  # Output: H
print(my_string[4])  # Output: o
print(my_string[-1])  # Output: !

In the first example, we access the first character of the string "Hello, World!" using its index number 0, which returns "H". In the second example, we access the fifth character using the index number 4, which returns "o". In the third example, we access the last character of the string using the negative index number -1, which returns "!".

  1. Negative Indexing

Negative indexing allows you to access the characters of a string from the end. In negative indexing, the index of the last character is -1, and the index of the second-last character is -2, and so on.

For example, let's consider the following string:

my_string = "Hello World"

To access the last character of the string using negative indexing, we can use:

print(my_string[-1])    # Output: d

Similarly, to access the second-last character, we can use:

print(my_string[-2])    # Output: l
  1. slicing

Slicing is another way to access a range of characters in a string. It involves specifying the start index, end index, and the step size.

Here's an example:

my_string = "Hello, world!"
substring = my_string[2:9:2]
print(substring)

Output:

lo,w

In the above example, we started slicing from index 2 (l) and stopped at index 9 (w) with a step size of 2. This means we got every second character between index 2 and 9.

Note that the start index is inclusive, while the end index is exclusive. This means that the character at the end index is not included in the slice.

Deleting Stings

In Python, we cannot delete or remove a part of a string. However, we can delete the entire string using the del keyword or by reassigning the string variable to an empty string.

Here is an example of deleting a string using the del keyword:

my_string = "Hello World!"
del my_string

After executing this code, the my_string variable will no longer exist in memory.

Here is an example of reassigning a string variable to an empty string:

my_string = "Hello World!"
my_string = ""

After executing this code, the my_string variable will still exist in memory, but its value will be an empty string.

String Methods

There are many built-in methods available in Python for manipulating strings. Here are some of the most commonly used ones:

  1. len(): Returns the length of the string.

  2. upper(): Converts all characters in the string to uppercase.

  3. lower(): Converts all characters in the string to lowercase.

  4. capitalize(): Converts the first character of the string to uppercase and the rest to lowercase.

  5. title(): Converts the first character of each word in the string to uppercase and the rest to lowercase.

  6. strip(): Removes any whitespace characters from the beginning and end of the string.

  7. replace(): Replaces all occurrences of a substring in the string with another substring.

  8. split(): Splits the string into a list of substrings based on a delimiter.

  9. join(): Joins a list of strings into a single string using a delimiter.

  10. find(): Searches the string for a substring and returns the index of the first occurrence.

  11. count(): Counts the number of occurrences of a substring in the string.

  12. startswith(): Returns True if the string starts with a given substring.

  13. endswith(): Returns True if the string ends with a given substring.

  14. isnumeric(): Returns True if all characters in the string are numeric.

  15. isalpha(): Returns True if all characters in the string are alphabetic.

  16. isdigit(): Returns True if all characters in the string are digits.

  17. isalnum(): Returns True if all characters in the string are alphanumeric.

  18. isspace(): Returns True if all characters in the string are whitespace characters.

These are just a few examples of the many string methods available in Python.

here are some examples of string methods:

  1. upper(): This method returns the string in uppercase letters.

string = "hello world"
print(string.upper()) # output: HELLO WORLD
  1. lower(): This method returns the string in lowercase letters.

string = "HELLO WORLD"
print(string.lower()) # output: hello world
  1. capitalize(): This method capitalizes the first letter of the string.

string = "hello world"
print(string.capitalize()) # output: Hello world
  1. split(): This method splits the string into a list of substrings based on a specified separator.

string = "apple,banana,orange"
print(string.split(",")) # output: ['apple', 'banana', 'orange']
  1. replace(): This method replaces a specified substring with another substring in the string.

string = "hello world"
print(string.replace("world", "python")) # output: hello python
  1. strip(): This method removes any leading and trailing whitespace from the string.

string = "   hello world   "
print(string.strip()) # output: hello world

String Formatting

String formatting is the process of creating a string that represents a value or a set of values in a specific way. In Python, there are several ways to format a string, including the %-formatting method, the str.format() method, and f-strings.

Here is an example using f-strings:

name = "Alice"
age = 30
print(f"My name is {name} and I'm {age} years old.")

This will output:

My name is Alice and I'm 30 years old.

In this example, the f-string is enclosed in curly braces {} and contains the variable names that we want to include in the string. The variables are automatically converted to strings and inserted into the string in the correct order.

Another way to format a string is by using the format() method:

name = "Bob"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))

This will output:

My name is Bob and I'm 25 years old.

In this example, the format() method is called on the string and the values to be inserted are passed as arguments in the correct order. The curly braces {} serve as placeholders for the values to be inserted.

The %-formatting method is another way to format strings in Python, but it is less commonly used than the format() method and f-strings.

Escape Characters

Escape characters are special characters that are used to represent certain characters that cannot be typed or are difficult to type. In Python, escape characters are represented by a backslash () followed by a character or a sequence of characters. Here are some commonly used escape characters in Python:

  • \n : newline

  • \t : tab

  • ' : single quote

  • " : double quote

  • \b : backspace

  • \r : carriage return

For example, if you want to print a string that contains a single quote, you can use the escape character like this:

print('I don\'t like Python.')

The output will be:

I don't like Python.

Triple Quotes

Triple quotes in Python are used to represent multiline strings. This means that strings can span across multiple lines and preserve the formatting of the text. Triple quotes can be used with both single and double quotes.

Triple quotes are commonly used for documentation strings (docstrings) in Python, which are used to document Python modules, functions, classes, and methods. They are enclosed in triple quotes, and can span multiple lines to provide detailed information about the code.

Here's an example of using triple quotes to create a multiline string:

my_string = '''This is a multiline
string in Python.
It can span across multiple lines
and preserve the formatting.'''
print(my_string)

Output:

This is a multiline
string in Python.
It can span across multiple lines
and preserve the formatting.

In the above example, the triple quotes allow us to create a multiline string that spans across four lines. The newlines and the formatting of the string are preserved when we print it to the console.

Python String Operations

Python provides various string operations that can be used to manipulate and process strings. Some of the commonly used string operations in Python are:

  1. Concatenation: It is used to join two or more strings together. The concatenation operator in Python is the plus sign (+).

  2. Repetition: It is used to repeat a string a certain number of times. The repetition operator in Python is the asterisk sign (*).

  3. Slicing: It is used to extract a part of a string. Slicing is done by specifying the start index and end index of the substring separated by a colon.

  4. Length: It is used to find the length of a string. The length of a string is the number of characters in the string.

  5. Case conversion: It is used to convert the case of the characters in a string. Python provides methods like upper(), lower(), title() to convert the case of the characters in a string.

  6. Strip: It is used to remove leading and trailing whitespaces from a string.

  7. Replace: It is used to replace a substring in a string with another substring.

  8. Find: It is used to find the first occurrence of a substring in a string.

  9. Count: It is used to count the number of occurrences of a substring in a string.

These operations make it easier to manipulate and process strings in Python.

Escape Sequences in Python

Last updated