Python Strings

Python Strings

kishore V


Python Strings

A string in Python is a sequence of characters used to represent text. Strings can be written using either single quotes (' ') or double quotes (" ")—both work exactly the same way.

Displaying a String

You can show text on the screen using the print() function.

Example:

Try it Yourself

Using Quotes Inside a String

You can include quotation marks inside a string as long as they are different from the quotes used to define the string.

Example:

Try it Yourself

Assigning a String to a Variable

Strings are commonly stored in variables so they can be reused later in a program.

Example:

Try it Yourself

Multi-Line Strings

Python allows you to store text across multiple lines using triple quotes (""" """ or ''' '''). Line breaks in the code are preserved in the output.

Example (Triple Double Quotes):

Try it Yourself

Example (Triple Single Quotes):

Try it Yourself

Strings as Sequences

In Python, strings behave like sequences (arrays) of Unicode characters. Each character has a position index, starting from 0.

Example:

Try it Yourself

This prints the character at index position 2.

Looping Through a String

Since strings are iterable, you can loop through each character using a for loop.

Example:

Try it Yourself

This prints each character on a new line.

Finding the Length of a String

Use the len() function to determine how many characters a string contains.

Example:

Try it Yourself

Checking for Text Inside a String

You can check whether a word or character exists in a string using the in keyword.

Example:

Try it Yourself

Using in with an if Statement

You can combine the in keyword with conditional statements to perform checks.

Example:

Try it Yourself

Checking if Text Is NOT Present

To verify that a word or character does not exist in a string, use the not in keyword.

Example:

Try it Yourself

Using not in with an if Statement

Example:

Try it Yourself

Python String Slicing

String slicing allows you to extract a specific portion of a string by selecting a range of characters. This is done using square brackets [] with a start index and an end index, separated by a colon.

    • The start index is inclusive, and the end index is exclusive.

    •  String indexing always begins at 0.

Basic Slice Syntax

Example:

Try it Yourself


This extracts characters starting from index 3 up to, but not including, index 7.

Slicing From the Beginning

If you omit the starting index, Python automatically begins slicing from the first character.

Example:

Try it Yourself


This returns the characters from the start of the string up to index 4.


Slicing Until the End

If you leave out the ending index, Python slices the string all the way to the last character.

Example:

Try it Yourself


This extracts everything from index 6 to the end of the string.

Using Negative Indexes

Negative indexing allows you to count characters from the end of the string.

    • -1 refers to the last character

    • -2 refers to the second-last character, and so on

Example:

Try it Yourself


This extracts characters starting from the 7th position from the end up to (but not including) the 3rd position from the end.

Modifying Strings in Python

Python provides many built-in methods that allow you to change or manipulate string values easily. These methods do not modify the original string—instead, they return a new modified string.

Converting Text to Uppercase

The upper() method converts all characters in a string to capital letters.

Example:

Try it Yourself

Converting Text to Lowercase

The lower() method changes all characters in a string to lowercase letters.

Example:

Try it Yourself

Removing Extra Spaces

Sometimes strings contain unwanted spaces at the beginning or end. The strip() method removes these extra spaces.

Example:

Try it Yourself


This is especially useful when working with user input.

Replacing Part of a String

The replace() method allows you to substitute one part of a string with another.

Example:

Try it Yourself

Splitting a String into a List

The split() method divides a string into a list based on a specified separator.

Example:

Try it Yourself


This is useful when processing CSV data, user input, or file content.

Combining Strings in Python

In Python, string concatenation means joining two or more strings into a single string. This is commonly done using the + operator.

Joining Two Strings

The + operator connects strings in the order they appear.

Example:

Try it Yourself

Adding Space Between Strings

When joining words, you often need to include a space manually

Example:

Try it Yourself

Concatenating Multiple Strings

You can also combine more than two strings at once.

Example:

Try it Yourself

Important Notes

    • Only strings can be concatenated using +

    • Numbers must be converted to strings before concatenation

    • For advanced formatting, Python also provides f-strings and format()

Python – String Formatting

In Python, strings and numbers cannot be directly joined using the + operator. Attempting to do so will raise a TypeError because Python treats text and numeric values as different data types.

Incorrect Example:

Try it Yourself

To safely combine text with numbers, Python provides string formatting techniques such as f-strings and the format() method.

Using F-Strings (Recommended)

F-strings (formatted string literals) were introduced in Python 3.6 and are now the most efficient and readable way to format strings.

To create an f-string:

    • Prefix the string with f

    • Place variables or expressions inside {}

Basic F-String Example

Try it Yourself

Placeholders in F-Strings

The expressions inside {} are called placeholders. They can include:

    • Variables

    • Mathematical expressions

    • Function calls

    • Formatting rules

Using Variables Inside Placeholders

Try it Yourself

Formatting Values with Modifiers

You can control how values appear using format specifiers.

A format modifier is added after a colon : inside the placeholder.

Formatting Floating-Point Numbers

Try it Yourself


✔ .1f → rounds the value to 1 decimal place

Using Expressions Inside F-Strings

F-strings can evaluate Python expressions directly.

Example:

Try it Yourself

Key Benefits of F-Strings

    • Cleaner and more readable syntax

    • Faster execution compared to older methods

    • Supports inline calculations and formatting

    • Ideal for real-world applications and APIs

Python – Escape Characters

Escape characters are special sequences used in Python strings to represent characters that cannot be typed directly or would otherwise break the string syntax.

An escape sequence always begins with a backslash (\), followed by a character that has a predefined meaning.

Why Escape Characters Are Needed

Some characters—such as quotes, new lines, or tabs—have special meanings in Python. If you try to use them directly inside a string, Python may throw a syntax error or interpret them incorrectly.

Problem Example (Without Escape Characters)

Try it Yourself


❌ This causes an error because the string ends before expected.

Using Escape Characters Correctly

You can safely include special characters by prefixing them with a backslash.

Correct Example

Output:

This is my "Python" program
Try it Yourself

Commonly Used Escape Characters

Single Quote (\')

Try it Yourself


Backslash (\\)

Try it Yourself


New Line (\n)

Try it Yourself


Tab Space (\t)

Try it Yourself


Carriage Return (\r)

Try it Yourself

Note: This moves the cursor to the beginning of the line.

Backspace (\b)

Try it Yourself


Form Feed (\f)

Try it Yourself


Numeric Escape Sequences

Try it Yourself


Hexadecimal Value (\xhh)

Try it Yourself



Our website uses cookies to enhance your experience. Learn More
Accept !