Python Strings

Strings are sequences of characters enclosed in single, double, or triple quotes. They are one of the most commonly used data types in Python for storing and manipulating text.

Creating Strings

You can create strings using single quotes, double quotes, or triple quotes for multi-line strings.

Single and double quotes can be used interchangeably. Triple quotes are useful for multi-line strings or strings that contain both single and double quotes.

Python

Tutorials dojo strip

Accessing Characters in a String

You can access individual characters in a string using indexing. Python uses zero-based indexing.

The index 0 accesses the first character, and the index 7 accesses the eighth character in the string.

Python

Slicing Strings

You can extract a substring from a string using slicing.

The slice 0:5 extracts characters from index 0 to 4, and the slice 7: extracts characters from index 7 to the end of the string.

Python

String Methods

Python provides several built-in methods for string manipulation.

1. upper()

Converts all characters in the string to uppercase.

Python

2. lower()

Converts all characters in the string to lowercase.

Python

3. strip()

Removes any leading and trailing spaces from the string.

Python

4. replace()

Replaces occurrences of the substring “World” with “Python”.

Python

5. split()

Splits the string at each comma, returning a list of substrings.

Python

String Formatting

Python Provides multiple ways to format strings.

1. Using the + operator:

Concatenates strings using the + operator and converts the integer age to a string.

Python


2. Using the format() method:

Uses the format() method to insert name and age into the string placeholders {}.

Python

3. Using f-strings (Python 3.6+):

Uses f-strings for inline variable interpolation, making the code more readable.

Python

Python Strings Example Code

This program creates a string and demonstrates various operations such as accessing characters, slicing, using string methods, and formatting strings.

Python




Python Labs

Tutorials dojo strip