Home »
Python
String operators with examples in python
Python string operators: Here, we are going to learn about the python string operators with examples in python.
Submitted by IncludeHelp, on April 02, 2019
String operators in Python
There are basically three operators which can be used with the string python:
- Python + Operator
- Python * Operator
- Python in Operator
1) Python "+" Operator
"+" Operator is known as concatenating operator in Python, it is used to concatenate/join two or more strings.
Example 1: Concatenating string variables
# python code to demonstrate an example
# of string "+" operator
str1 = "Hello"
str2 = " "
str3 = "world!"
result = str1+str2+str3
print("str1: ", str1)
print("str2: ", str2)
print("str3: ", str3)
print("result: ", result)
Output
str1: Hello
str2:
str3: world!
result: Hello world!
Example 2: Adding strings, string variables within the print() function
# python code to demonstrate an example
# of string "+" operator
name = "prem"
print("My name is " + name)
print("Hello" + " " + "world!")
Output
My name is prem
Hello world!
2) Python "*" Operator
" * " Operator is used to create multiple copies of a string.
Example 1:
# python code to demonstrate an example
# of string "*" operator
result1 = "Hello"*3
print("result1: " + result1)
strval = "Hello world "
n = 5
result2 = strval*n
print("result2: " + result2)
Output
result1: HelloHelloHello
result2: Hello world Hello world Hello world Hello world Hello world
Example 2: Testing with zero or negative value
If we multiply a string with either 0 (zero) or a negative number, the result will be an empty string.
# python code to demonstrate an example
# of string "*" operator
result1 = "Hello"* 0
print("result1: " + result1)
strval = "Hello world "
n = -5
result2 = strval*n
print("result2: " + result2)
Output
result1:
result2:
3) Python "in" Operator
"in operator" is used to check whether a given value (first operand) exists in the string (second operand) or not. It returns True if the first operand exists in the second operand, else it returns False.
Example:
# python code to demonstrate an example
# of string "in" operator
str1 = "IncludeHelp.com is very popular"
str2 = "is"
if str2 in str1:
print("\'" + str2 + "\'" + " exists in " + str1)
else:
print("\'" + str2 + "\'" + " does not exist in " + str1)
str2 = "are"
if str2 in str1:
print("\'" + str2 + "\'" + " exists in " + str1)
else:
print("\'" + str2 + "\'" + " does not exist in " + str1)
Output
'is' exists in IncludeHelp.com is very popular
'are' does not exist in IncludeHelp.com is very popular
ADVERTISEMENT
ADVERTISEMENT