Skip to main content

Command Palette

Search for a command to run...

Strings Support More Operators Than I Expected: Concatenation, Comparison, and More

Updated
•4 min read•View as Markdown
Strings Support More Operators Than I Expected: Concatenation, Comparison, and More
D

A dedicated Computer Engineering graduate from SCET. Throughout my academic journey, I navigated the dynamic landscape of education during the challenging Covid era, which instilled in me resilience and adaptability. My experience in the field of Data Engineering spans across Transact SQL, MS SQL Server, Agile Methodologies, and a foundational understanding of Azure Data Factory and various cloud services. These experiences have not only honed my technical acumen but also reinforced my capacity to thrive in diverse and evolving environments.

My current pursuits reflect a keen interest in expanding my knowledge in both DevOps and Cloud Engineering. Alongside these technical endeavors, I'm fervently learning Full Stack Web Development from the ground up, eager to explore the intricate interplay of front-end and back-end systems.

Embracing a holistic approach to problem-solving, I'm delving into the intricacies of System Design, striving to develop comprehensive and efficient solutions within the IT industry. Building on approximately 6 months to 1-year of hands-on industry experience, I'm driven to continuously enhance my skill set, contributing meaningfully to the technological landscape.

Beyond the realms of technology, I find solace in capturing the ephemeral beauty of sunsets through photography, letting the time freeze those breathtaking moments. Music is my constant companion, offering relaxation and inspiration. As an avid cricket enthusiast, the game brings camaraderie and excitement.

I'm always open to connecting with fellow professionals, learning from shared experiences, and contributing to the ever-evolving tech sphere. Let's connect and explore the limitless possibilities together!

Strings aren't just something you slice and index. They also respond to a surprising number of the operator categories from earlier in this series, arithmetic, relational, logical, and membership, each behaving in ways specific to text.

Arithmetic: only two operators actually apply

Out of all the arithmetic operators, only + and * work on strings.

print("Hi" + "everyone")        # Hieveryone, no space, exactly as written
print("Hi" + " " + "everyone")  # Hi everyone

+ concatenates strings together, exactly as written, with no automatic spacing added.

print("Hi" * 5)   # HiHiHiHiHi
print("*" * 10)   # **********

* repeats a string a given number of times. This second one turns out to be genuinely useful, printing a row of characters for a pattern or a table border is a lot cleaner as "*" * 10 than typing ten asterisks by hand.

Relational operators: comparing strings like dictionary order

print("hello" == "hello")   # True
print("hello" != "world")   # True
print("hello" > "hi")       # False
print("hello" < "world")    # True
print("hello" >= "hello")   # True

Term check: lexicographic order Strings compare character by character based on each character's underlying code point, which lines up closely with dictionary (alphabetical) order for everyday text. "hello" comes before "hi" the same way it would in a dictionary, since comparing the second letter, 'e' sorts before 'i'.

This one is a genuinely common interview question, even though it rarely comes up directly while building real projects, so it's worth being able to explain in plain words rather than just trusting the operator to do the right thing.

Logical operators: strings have a truth value

print("hello" and "world")  # world
print("hello" or "world")   # hello
print("" and "world")       # '' (empty string)
print("" or "world")        # world
print(not "hello")          # False

Term check: truthy and falsy Every value in Python has an implicit true/false quality, even when it isn't a literal True or False. A non-empty string is "truthy," and an empty string "" is "falsy." This is what and/or are actually checking behind the scenes when applied to strings, not the string's content, just whether it's empty or not.

and returns the second value once both operands are truthy, since it needs to confirm both are "on" before deciding the overall result. or returns the first truthy value it finds, short-circuiting as soon as one side is confirmed true.

Looping over a string, revisited

This one's a callback to the loops posts: a for loop iterates over a string one character at a time.

for letter in "Darshan":
    print("Hello")

This prints "Hello" seven times, once per character in "Darshan", regardless of what the actual letters are. The loop body runs once per character in the sequence, it's not inspecting the letters here at all, just counting through them.

Membership operators, refreshed

Another callback, this time to the operators post: in and not in work directly on strings.

print("D" in "Darshan")       # True
print("D" not in "Darshan")   # False
print("x" in "Darshan")       # False
print("x" not in "Darshan")   # True

Common mistakes I'd flag here

  • Expecting + to add a space automatically between concatenated strings. It doesn't, any spacing has to be added explicitly.

  • Trying arithmetic operators beyond + and * on strings (like - or /), which aren't supported and throw a TypeError.

  • Assuming and/or on strings return True/False the way they do on plain booleans. They actually return one of the original strings, based on which one is truthy.

  • Forgetting that an empty string is falsy, which can quietly change the outcome of a condition that expected a string to just always count as true.

Quick recap

  • Strings only support two arithmetic operators: + for concatenation and * for repetition.

  • Relational operators compare strings using lexicographic (roughly dictionary) order, based on each character's underlying code point.

  • Logical operators treat empty strings as falsy and non-empty strings as truthy, and return one of the actual operand strings rather than a plain True/False.

  • Looping over a string iterates through it one character at a time.

  • Membership operators (in, not in) check whether a character or substring exists within a string.

What's next

Next up: Python's built-in string functions/methods, the ready-made tools for things like changing case, trimming whitespace, and searching within a string, instead of writing that logic manually.

Bite-Sized Python: Zero to Modular Code

Part 13 of 16

Learning to code or pivoting into modern software development can feel like wading through an ocean of tutorials. In this series, I document my hands-on journey through Python, breaking down every core concept into plain-English explanations, visual mental models, and ready-to-use code snippets. Whether you are writing your first print() statement or learning how to structure production-ready modular applications, follow along as we build our skills one post at a time.

Up next

Python's String Methods Turned Out to Be a Cheat Code

Up to this point I've been doing a lot of string work manually: indexing, slicing, writing my own loops to check things. Turns out Python ships a whole toolbox of ready-made string methods that handle

More from this blog

The Accidental Techie: Darshan Joshi

20 posts

Code creator by day, deep thinker by night✨ weaving bytes and pondering life's algorithms❤

A dedicated Computer Engineering graduate from SCET. Throughout my academic journey, I navigated the dynamic landscape of education during the challenging Covid era, which instilled in me resilience and adaptability. My experience in the field of Data Engineering spans across Transact SQL, MS SQL Server, Agile Methodologies, and a foundational understanding of Azure Data Factory and various cloud services. These experiences have not only honed my technical acumen but also reinforced my capacity to thrive in diverse and evolving environments.

My current pursuits reflect a keen interest in expanding my knowledge in both DevOps and Cloud Engineering. Alongside these technical endeavors, I'm fervently learning Full Stack Web Development from the ground up, eager to explore the intricate interplay of front-end and back-end systems.

Embracing a holistic approach to problem-solving, I'm delving into the intricacies of System Design, striving to develop comprehensive and efficient solutions within the IT industry. Building on approximately 6 months to 1-year of hands-on industry experience, I'm driven to continuously enhance my skill set, contributing meaningfully to the technological landscape.

Beyond the realms of technology, I find solace in capturing the ephemeral beauty of sunsets through photography, letting the time freeze those breathtaking moments. Music is my constant companion, offering relaxation and inspiration. As an avid cricket enthusiast, the game brings camaraderie and excitement.

I'm always open to connecting with fellow professionals, learning from shared experiences, and contributing to the ever-evolving tech sphere. Let's connect and explore the limitless possibilities together!