String Operations in Python
Python allows several operations on strings like joining, repeating, checking membership, and comparing. These are useful for performing various tasks while handling text.
Types of String Operations:
- Concatenation
- Repetition
- Membership Operators
- String Comparison
1. Concatenation
Concatenation means joining two or more strings together. It uses the
+ (plus) operator to merge strings.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
Output: Hello World
Explanation:
- The + operator joins the strings.
- A space
" "is added manually between the two words.
2. Repetition
Repetition means repeating the same string multiple times. It uses the
* (asterisk) operator.
text = "Hi "
print(text * 3)
Output: Hi Hi Hi
Explanation:
- The string "Hi " is printed 3 times.
- Repetition operator helps in patterns or repeated text output.
3. Membership Operators
Membership operators check whether a substring exists in the main string or not. It
uses in and not in keywords.
message = "Python is fun"
print("fun" in message)
print("easy" not in message)
Output:
True
True
Explanation:
"fun" in messageis True because "fun" is present."easy" not in messageis True because "easy" is missing.
4. String Comparison
String comparison means checking whether two strings are equal, or which one is
greater alphabetically.
In Python, we use comparison operators to compare strings. It uses operators like
==, !=,
>, <, etc.
Example:
a = "apple"
b = "banana"
print(a == b)
print(a < b)
Output:
False
True
Explanation:
a == bgives False because the strings "apple" and "banana" are not the same.a < bgives True because in alphabetical (dictionary) order, "apple" comes before "banana".- Python compares each character using their Unicode values. First letters
'a' and 'b' are compared. Since 'a' comes before 'b', the result is
True.
Important Points:
- String comparison is case-sensitive. "Apple" and "apple" are considered different.
- Strings are compared based on dictionary (alphabetical) order.
Summary:
- + joins strings (concatenation).
- * repeats the string multiple times.
- in / not in checks if substring exists.
- ==, !=, >, < used for comparing strings.