top of page

Strings

  • Shreyas Naphad
  • Jun 17, 2024
  • 2 min read

In this article, we will be understanding the concept of a string. Before understanding the technical aspects, let's first understand strings with an easy real-life example.

Imagine strings as sentences in a book. Each sentence will contain letters, words, and punctuation marks, all combined to convey a message or information.

Similarly, strings allow us to store and manipulate text so that we can display and modify the text as and when needed.


Example:

So we have a sentence that we want to store and this sentence will be contained within a string. So, for this, we can use a string where all the characters of the sentence are stored together. The syntax that will be used is for Python.

sentence = "Hello"

Now, if we want to get the first letter of this sentence, we know that it is 'H'. It is important to note that strings are indexed starting from 0, so the index of 'H' is 0.

first_letter = sentence[0]  # Indexing starts from 0

So, the formal definition of a string is that a string is a sequence of characters used to represent text. These characters are stored in contiguous memory locations.


Types of Strings:

1.    Single-line Strings: These strings consist of a single line of text. For example, a greeting message "Hello World" is a single-line string.

2.    Multi-line Strings: These strings contain multiple lines and are useful for storing large blocks of text. In Python, multi-line strings are created using triple quotes.

multi_line_string = """This is a string

that has multiple

lines."""

3.    Immutable Strings: Most programming languages treat strings as immutable, meaning that once a string is created, it cannot be changed. Any modification creates a new string.


Key Points About Strings:

1.    Contiguous Memory Allocation: When a string is created, the characters are stored in contiguous memory locations, making access fast and efficient.

2.    Fixed Content: Strings are immutable in many programming languages. This means once a string is created, its content cannot be changed.

3.    Zero-based Indexing: The indexing of characters in a string starts from 0, similar to arrays.

4.    Random Access: Strings allow random access, meaning we can access any character in the string using its index.


Common String Operations:

1.    Concatenation: Joining two or more strings together.

salutation = "Hello, " + "world!"

2.    Substring: Extracting a part of a string.

sub = salutation [0:5]  # "Hello"

3.    Length: Finding the number of characters in a string.

length = len(salutation)  # 13

4.    Replacement: Replacing a part of a string with another string.

new_greeting = salutation.replace("world", "everyone")  # "Hello,  everyone!"

Comentarios


©2025 by DevSparks.

bottom of page