String Operators

Code Examples

Example 1

The + operator joins strings together. Here we combine first name, a space, and last name to create a full name.

first_name = "John"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)  # Output: John Smith

Example 2

The * operator repeats a string a specified number of times. This is useful for creating patterns or decorative elements.

laugh = "ha"
big_laugh = laugh * 5
print(big_laugh)  # Output: hahahahahaha

border = "-" * 20
print(border)  # Output: --------------------

Example 3

The "in" operator checks if one string exists inside another string. It returns True if found, False if not.

sentence = "The quick brown fox"
print("fox" in sentence)    # Output: True
print("cat" in sentence)    # Output: False

email = "user@gmail.com"
if "@" in email:
    print("Valid email format")  # This will print

Example 4

The not in operator checks if a string does NOT exist inside another string. Useful for validation and filtering.

password = "mypassword123"
if "!" not in password:
    print("Password should contain special characters")  # This will print

forbidden_words = ["spam", "virus", "hack"]
message = "Hello there!"
if "spam" not in message:
    print("Message is clean")  # This will print

Example 5

== checks if strings are exactly the same != checks if strings are different < and > compare strings alphabetically (lexicographically)

# Equality
user_input = "yes"
if user_input == "yes":
    print("User agreed")  # This will print

# Inequality
status = "active"
if status != "inactive":
    print("User is active")  # This will print

# Alphabetical comparison
name1 = "Alice"
name2 = "Bob"
print(name1 < name2)  # Output: True (Alice comes before Bob alphabetically)

Example 6

This example combines multiple string operators to create a simple validation system, showing how these operators work together in real applications. These string operators are fundamental building blocks that you'll use constantly in Python programming for text processing, user input validation, and creating dynamic messages.

# User registration system
username = "john_doe"
password = "secret123"

# Check username requirements
if len(username) >= 5 and "_" in username:
    print("Username format is good")
else:
    print("Username must be at least 5 characters and contain underscore")

# Check password requirements  
if len(password) >= 8 and any(char.isdigit() for char in password):
    print("Password meets requirements")
else:
    print("Password must be at least 8 characters with numbers")

# Create welcome message
welcome = "Welcome, " + username + "!"
print(welcome)  # Output: Welcome, john_doe!