Python – String Operators

Python-String-Operators

String Operators 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
>>> 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
>>> 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
>>> str1 = "Let's start preparing!"
>>> "!" in str1
True
>>> "?" in str1
False
>>> "?" not in str1
True