python
  1. python-strings

Python Strings

In Python, a string is a sequence of characters enclosed within single quotes ('') or double quotes (""). Strings are immutable which means once they are created, the values cannot be changed. In this article, we will cover the various operations that can be performed on strings in Python.

Syntax

my_string = "Hello World"

Example

Here are some examples of strings in Python:

# Single line string
str1 = "Hello World"

# Multi-line string using triple quotes
str2 = """This is a 
multi-line string"""

# Accessing characters in a string
print(str1[0])      # Output: H
print(str2[7:10])   # Output: is 

Output

H
is 

Explanation

In the above example, single line string is created using single quotes and multi-line string is created using triple quotes. The characters in a string are accessed by their index. In Python, the first character of a string has an index 0, and the index increases by 1 for every subsequent character.

Operations on Strings

Strings in Python support a lot of operations, including concatenation, repetition, slicing, formatting, and more.

Concatenation

Concatenation is the process of joining two or more strings together. This is done using the + operator.

# Example of string concatenation
str1 = "Hello"
str2 = "World"
str3 = str1 + " " + str2
print(str3)         # Output: Hello World

Repetition

Repetition is the process of repeating a string a specified number of times. This is done using the * operator.

# Example of string repetition
str1 = "Hello"
str2 = str1 * 3
print(str2)         # Output: HelloHelloHello

Slicing

Slicing is the process of extracting a substring from a string. This is done using the [] operator.

# Example of string slicing
str1 = "Hello World"
print(str1[6:11])    # Output: World

Formatting

Formatting is the process of inserting values into a string. This is done using the {} operator.

# Example of string formatting
name = "Alice"
age = 25
msg = "My name is {} and I am {} years old".format(name, age)
print(msg)          # Output: My name is Alice and I am 25 years old

Important Points

  • Strings are immutable in Python.
  • Strings can be created using either single quotes or double quotes.
  • Strings support a lot of operations, including concatenation, repetition, slicing, formatting, and more.

Summary

In this article, we covered the basics of strings in Python and learned about the various operations that can be performed on strings. We also learned that strings are immutable in Python, and saw examples of string concatenation, repetition, slicing, and formatting.

Published on: