PythonHandling StringsCore String Operations

Core String Operations

Beyond the basics of creating and accessing strings, Python provides a set of core operations using standard operators. These allow for concise and readable manipulation of text.

1. Concatenation: Combining Strings

You can “add” strings together using the + operator. This joins them to create a new string.

Pyground

Combine a first name and a last name with a space in between.

Expected Output:

Rhea Kapoor

Output:

️🐢

Performance Note: While + is fine for a few strings, joining many strings in a loop this way is inefficient because it creates a new string object at every step. For joining many items, str.join() is the preferred, high-performance method.

Pyground

Join a list of words into a single sentence using `str.join()`.

Expected Output:

Python is incredibly versatile

Output:

2. Repetition: Repeating Strings

You can multiply a string by an integer n using the * operator to create a new string that consists of the original repeated n times.

Pyground

Create a decorative banner by repeating the '=' character 30 times.

Expected Output:

==============================
Important Message
==============================

Output:

3. Membership Testing: in and not in

You can check if a substring exists within a larger string using the in and not in operators. These return a boolean value (True or False).

Pyground

Check if the word 'learning' is present in a sentence.

Expected Output:

Does the sentence contain 'learning'? True
Does the sentence contain 'Java'? False

Output:

4. String Comparisons

You can use standard comparison operators (==, !=, <, >, <=, >=) to compare strings. The comparison is done lexicographically, character by character, based on their Unicode code point values (which for English letters corresponds to alphabetical order).

Equality checks are case-sensitive.

Pyground

Compare 'python' and 'Python' for equality.

Expected Output:

'python' == 'Python': False
'python'.lower() == 'Python'.lower(): True

Output:

Lexicographical comparison means that uppercase letters are considered “less than” lowercase letters. For example, 'Z' < 'a' is True.

5. Accessing Characters (Recap)

As covered in the basics, you can access characters and substrings using indexing and slicing. These are core operations that don’t use traditional operators but are fundamental to string manipulation.

Pyground

Given a full name, extract the first name and the last initial.

Expected Output:

First Name: John
Last Initial: D.

Output: