Python – String Operators
String Operators in Python
In Python – String Operators functions same as numeric operators the only difference is that string operators are used to manipulate strings while numeric operators are used to manipulate numbers. In this tutorial you will see how string operators works and how to use them in code.
String Operators
There are few operators in python which can be used with numeric operands as well as strings:
- The “+” operator
- The “*” operator
Besides this two there is one membership operator which can be used on all sequences like string, list etc.
- The “in” operator
Let’s discuss what this operators do in detail:
The “+” operator
- Concatenates strings: Returns a string consisting of the operands joined together
Run
>>> str1 = "Prep" >>> str2 = "Insta" >>> str1+str2 'PrepInsta' >>> print("Hello"+" "+"team"+"!") "Hello team!"
The “*” operator
- Creates multiple copies of strings: Returns a string consisting of the n concatenated copies of a string
Run
>>> str1 = "Prep" >>> n = 3 >>> str1 * n 'PrepPrepPrep' >>> (str1 + " " )*n 'Prep Prep Prep ' >>> str1*-2 '' # if negative integer is used with * operator then an empty string(" ") is returned >>> str1*3 'PrepPrepPrep'
The “in” operator
- A membership operator that can be used with strings
- returns True if the first operand is contained within the second
- returns False otherwise
- also can be used as not in
Run
>>> str1 = "Let's start preparing!" >>> "!" in str1 True >>> "?" in str1 False >>> "?" not in str1 True
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment