DEV Community

Cover image for Strings in Python
Mahalakshmi C
Mahalakshmi C

Posted on

Strings in Python

Introduction

In Python, a string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes.

Strings are used to store text, such as names, addresses, messages, and sentences.

Python supports three ways to create strings:

  1. Single quotes (' ')
  2. Double quotes (" ")
  3. Triple quotes (''' ''' or """ """)

Example

name = 'maha'
name2 = "lakshmi"

print(name)
print(name2)

print(type(name))
print(type(name2))
Enter fullscreen mode Exit fullscreen mode

Output:

maha
lakshmi
<class 'str'>
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

Explanation

  • name stores the string maha using single quotes.
  • name2 stores the string lakshmi using double quotes.
  • The type() function identifies the datatype of a variable.
  • Both variables belong to the str datatype.

Note: In Python, datatypes are represented by classes. For example, str is the class used for string objects.

2. String Methods

Python provides several built-in string methods to perform operations on strings.

One such method is capitalize().

Example: capitalize()

name = "maha"

print(name.capitalize())
Enter fullscreen mode Exit fullscreen mode

Output:

Maha
Enter fullscreen mode Exit fullscreen mode

Explanation

The capitalize() method converts the first character of a string to uppercase and the remaining characters to lowercase.

Important: Strings are immutable in Python. This means we cannot modify the original string directly. String methods return a new string.

3. Multiline Strings

Sometimes we need to store multiple lines of text in a single variable.

For this purpose, Python supports triple quotes.

Example

address = """7, Vivekanandar Street,
            West Tambaram,
            Chennai"""

print(address)
Enter fullscreen mode Exit fullscreen mode

Output:

7, Vivekanandar Street,
            West Tambaram,
            Chennai
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Triple quotes allow us to write strings across multiple lines.
  • Line breaks are preserved in the string.
  • Multiline strings are useful for storing addresses, paragraphs, and long messages.

4. What Is String Indexing?

Indexing is used to access individual characters from a string.

In Python, every character in a string has an index position.

Python supports two types of indexing:

  1. Positive indexing
  2. Negative indexing

Positive Indexing

Positive indexing starts from 0, moving from left to right.

Consider the following string:

word = 'python'
Enter fullscreen mode Exit fullscreen mode

Positive index positions

Character p y t h o n
Index 0 1 2 3 4 5

Negative Indexing

Negative indexing starts from -1, moving from right to left.

Character p y t h o n
Index -6 -5 -4 -3 -2 -1

Example

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[1])
print(word[5])
print(word[-2])
Enter fullscreen mode Exit fullscreen mode

Output:

b
f
y
Enter fullscreen mode Exit fullscreen mode

Explanation

  • word[1] returns the character at index 1, which is b.
  • word[5] returns the character at index 5, which is f.
  • word[-2] returns the second character from the end, which is y.

Important: If we try to access an index that does not exist, Python raises an IndexError.

5. What Is String Slicing?

Slicing is used to extract a part of a string.

Syntax

string[start:stop:step]
Enter fullscreen mode Exit fullscreen mode

Here:

  • start: The index where slicing begins.
  • stop: The index where slicing ends. The stop position is not included.
  • step: The number of positions to move each time.

Example 1: Basic Slicing

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[1:5])
Enter fullscreen mode Exit fullscreen mode

Output:

bcde
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Slicing starts at index 1.
  • It stops before index 5.
  • Therefore, the characters at indexes 1, 2, 3, and 4 are returned.

Example 2: Slicing with Step

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[2:10:2])
Enter fullscreen mode Exit fullscreen mode

Output:

cegi
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Starting index is 2.
  • Ending index is 10 (not included).
  • Step value is 2.
  • Python selects every second character.

Example 3: Start Value Greater Than Stop Value

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[20:2])
Enter fullscreen mode Exit fullscreen mode

Output:

(empty string)
Enter fullscreen mode Exit fullscreen mode

Explanation:

The default step is positive 1, so Python moves from left to right.

Since the starting index 20 is greater than the stopping index 2, no characters are selected.

Example 4: Slicing with Step 2

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[20::2])
Enter fullscreen mode Exit fullscreen mode

Output:

uwy
Enter fullscreen mode Exit fullscreen mode

Explanation:

Python starts at index 20 and moves forward by 2 positions until the end of the string.

Example 5: Negative Slicing

word = 'abcdefghijklmnopqrstuvwxyz'

print(word[-1:-10:-2])
Enter fullscreen mode Exit fullscreen mode

Output:

zxvtr
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Starting index is -1.
  • Stopping index is -10 (not included).
  • Step is -2.
  • A negative step moves from right to left.

6. Reversing a String Using Slicing

We can reverse a string using slicing with a negative step.

Example

name = 'python'

print(name)
print(name[-1:])
print(name[-1::-1])
print(name[::-1])
print(name[-1::])
Enter fullscreen mode Exit fullscreen mode

Output:

python
n
nohtyp
nohtyp
n
Enter fullscreen mode Exit fullscreen mode

Explanation

1. name

Prints the complete string.

2. name[-1:]

Starts from the last character and takes the remaining characters. Since it is already at the end, only n is returned.

3. name[-1::-1]

Starts from the last character and moves backwards through the string.

4. name[::-1]

Reverses the entire string using a negative step.

5. name[-1::]

Starts from the last character and moves forward. Therefore, it returns only n.

Top comments (0)