Strings in Python

Python : Strings

A string is a sequence of characters enclosed within either single quotes ('...') or double quotes ("..."). Strings are immutable, which means that once a string is created, it cannot be modified.

String Operations in Python

Strings in Python support a wide range of operations such as indexing, slicing, concatenation, and repetition etc. Here we will discuss some important and frequently used operations with examples -

Creating a string in Python

To create a string, you can simply assign a value to a variable using either single or double quotes:

string1 = 'Hello World!'
string2 = "My name is John."

String indexing in Python

In Python, you can access individual characters in a string by using an index. The index starts at 0 for the first character and goes up to n-1 for the nth character, where n is the length of the string.

string = "Hello"
print(string[0]) # Output: 'H'
print(string[1]) # Output: 'e'
print(string[2]) # Output: 'l'
print(string[3]) # Output: 'l'
print(string[4]) # Output: 'o'

String slicing in Python

You can also access a substring from a string using slicing. The syntax for slicing is string[start:stop:step]. The start index is inclusive and the stop index is exclusive. The step value is optional and defaults to 1. For example:

string = "Hello World!"
print(string[0:5]) # Output: 'Hello'
print(string[6:])  # Output: 'World!'
print(string[::-1]) # Output: '!dlroW olleH'

String concatenation in Python

You can concatenate two or more strings using the + operator.

string1 = "Hello"
string2 = "World"
print(string1 + " " + string2) # Output: 'Hello World'

String repetition in Python

You can repeat a string multiple times using the * operator.

string = "Hello"
print(string * 3) # Output: 'HelloHelloHello'

String formatting in Python

You can format a string using the format() method. This allows you to replace placeholders in a string with values.

name = "John"
age = 30
print("My name is {} and I am {} years old".format(name, age))
# Output: 'My name is John and I am 30 years old'

String Methods in Python

Strings have many built-in methods that you can use to manipulate them.

text = "   This is some text.   "
print(text.strip())    # Remove whitespace from the beginning and end of the string
print(text.lower())    # Convert the string to lowercase
print(text.upper())    # Convert the string to uppercase
print(text.replace("text", "sentence"))    # Replace a substring with another substring


"This is some text."
"   this is some text.   "
"   This is some sentence.   "

String Encoding/Decoding in Python

You can encode a string to a different character encoding or decode a string from a different character encoding using the encode() and decode() methods.

text = "Hello, world!"
encoded_text = text.encode("base64")
decoded_text = encoded_text.decode("base64")

# Output
# "SGVsbG8sIHdvcmxkIQ==\n"
# "Hello, world!"

String Searching and Manipulation in python

String searching and manipulation are important tasks in programming, especially when dealing with large amounts of text data.

In Python, there are several built-in methods and functions that can be used to perform string searching and manipulation, here we will discuss some of them-

  • Searching for Substrings in python

    We can use the find() method to search for a substring within a larger string. The find() method returns the index of the first occurrence of the substring, or -1 if the substring is not found.

    text = "The quick brown fox jumps over the lazy dog"
    index = text.find("fox")
    print(index)   # Output: 16
  • Replacing Substrings in python

    We can use the replace() method to replace one substring with another within a larger string. The replace() method returns a new string with the substitutions made.

    text = "The quick brown fox jumps over the lazy dog"
    new_text = text.replace("fox", "cat")
    print(new_text)   # Output: "The quick brown cat jumps over the lazy dog"
  • Changing Case in python

    We can use the lower() and upper() methods to change the case of a string to lowercase or uppercase, respectively.

    text = "The quick brown fox jumps over the lazy dog"
    lower_text = text.lower()
    upper_text = text.upper()
    print(lower_text)   # Output: "the quick brown fox jumps over the lazy dog"
    print(upper_text)   # Output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
  • Stripping Whitespace in python

    We can use the strip() method to remove any leading or trailing whitespace from a string.

    text = "   The quick brown fox jumps over the lazy dog   "
    new_text = text.strip()
    print(new_text)   # Output: "The quick brown fox jumps over the lazy dog"
  • Splitting and Joining Strings in python

    We can use the split() method to split a string into a list of substrings based on a delimiter, and the join() method to join a list of substrings into a single string using a delimiter.

    text = "The quick brown fox jumps over the lazy dog"
    words = text.split(" ")
    print(words)   # Output: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
    new_text = "-".join(words)
    print(new_text)   # Output: "The-quick-brown-fox-jumps-over-the-lazy-dog"

Introduction to List in Python