String Operations

In Python, strings are a sequence of characters and are used to represent textual data. The built-in string type in Python is str. Strings are often used for representing names, addresses, descriptions, and many other types of textual data. In this section, we will learn about various string operations in Python.

  1. Concatenation of Strings: Strings can be concatenated using the + operator. This means that we can add two or more strings together to form a new string. For example:
string1 = "Hello"
string2 = "World"
string3 = string1 + string2
print(string3)

This code will output HelloWorld.

  1. Repetition of Strings: Strings can also be repeated using the * operator. This means that we can repeat a string multiple times to form a new string. For example:
string = "Hello"
string_repeated = string * 3
print(string_repeated)

This code will output HelloHelloHello.

  1. Accessing Characters in a String: In Python, strings are sequences of characters, and we can access individual characters within a string using square brackets. For example:
string = "Hello"
first_character = string[0]
print(first_character)

This code will output H.

  1. Slicing Strings: Slicing in Python allows us to extract a portion of a string. Slicing is performed by specifying a start and end position within square brackets. For example:
string = "Hello"
sliced_string = string[1:4]
print(sliced_string)

This code will output ell.

  1. String Methods: Python provides a number of built-in string methods that can be used to perform operations on strings. Some of the most commonly used string methods include:
  • len(): Returns the length of the string.
  • str.upper(): Returns the string in uppercase.
  • str.lower(): Returns the string in lowercase.
  • str.replace(): Replaces a portion of the string with another string.
  • str.split(): Splits the string into a list of substrings based on a specified separator.

For example:

string = "Hello World"
length = len(string)
print(length)

uppercase = string.upper()
print(uppercase)

lowercase = string.lower()
print(lowercase)

replaced_string = string.replace("Hello", "Goodbye")
print(replaced_string)

split_string = string.split(" ")
print(split_string)

This code will output:

11
HELLO WORLD
hello world
Goodbye World
['Hello', 'World']

In conclusion, strings are a fundamental aspect of programming in Python, and there are many operations that can be performed on them. By understanding these operations, we can effectively manipulate and work with strings in our Python programs.