There are mainly three operators for string.
- Mathematical Operators
- Membership Operators
- Comparison Operators
Mathematical Operators
- We can apply the following mathematical operators for Strings.
- + ⇒ operator for concatenation
- * ⇒ operator for repetition
Example
Python
print("internet"+"knowledge"+"hub")
print("internet"*3)
Output
PowerShell
internetknowledgehub
internetinternetinternet
Remark
- To use + operator for Strings, compulsory both arguments should be str type.
- To use * operator for Strings, compulsory one argument should be str and other argument should be int.
Membership Operators
- We can check whether the character or string is the member of another string or not by using “in” and “not in” operators.
Example
Python
s=input("Enter main string:")
subs=input("Enter sub string:")
if subs in s:
print(subs,"is found in main string")
else:
print(subs,"is not found in main string")
Output
PowerShell
Enter main string:internetknowledgehub
Enter sub string:internet
internet is found in main string
PowerShell
Enter main string:internetknowledgehub
Enter sub string:python
python is not found in main string
Comparison Operators
- We can use comparison operators (<, <=, >, >=) and equality operators (==, !=) for strings.
- Comparison will be performed based on alphabetical order.
Example
Python
s1=input("Enter first string:")
s2=input("Enter Second string:")
if s1==s2:
print("Both strings are equal")
elif s1<s2:
print("First String is less than Second String")
else:
print("First String is greater than Second String")
Output
PowerShell
Enter first string:internet
Enter Second string:internet
Both strings are equal
PowerShell
Enter first string:ajay
Enter Second string:amit
First String is less than Second String
PowerShell
Enter first string:amit
Enter Second string:ajay
First String is greater than Second String
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!