Python String Operators with Examples

By IncludeHelp Last updated : December 2, 2023

Python provides many operators to work with the strings. Python string operators are used for adding multiple strings, repeating strings multiple times, checking substring in a string, etc. In this tutorial, we will learn about some of the popular string operators.

Python String Operators

The following are the string operators in Python:

  1. Python String Assignment (=) Operator
  2. Python String Concatenate (+) Operator
  3. Python String Repetition (*) Operator
  4. Python String Slicing ([]) Operator
  5. Python String Comparison (== and !=) Operators
  6. Python String Membership (in and not in) Operators
  7. Python String Escape Sequence (\) Operator
  8. Python String Formatting (% and {}) Operators

1. Python String Assignment (=) Operator

Python string assignment operator is =, it assigns string values to the variable.

Example

This example demonstrates the use of assignment operator.

# Assigning string values to variables
a = "Hello"
b = "World"
c = """Hello,
world!
"""

# Printing the values of variables
print(a)
print(b)
print(c)

Output:

The output of the above example is:

Hello
World
Hello,
world!

2. Python String Concatenate (+) Operator

The + 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:

The output of the above example is:

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:

The output of the above example is:

My name is prem
Hello world!

3. Python String Repetition (*) Operator

The * operator is used to create multiple copies of a string.

Example 1: Use of string repetition (*) operator

# 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:

The output of the above example is:

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:

The output of the above example is:

result1:
result2:

4. Python String Slicing ([]) Operator

String slicing means accessing a substring from the given string, this can be done by using a simple syntax.

string_name[beg:end:step]

Here,

  • beg : is the beginning index
  • end : is the end index but end is not inclusive
  • step : distance between every word (steps are optional)

Note! If step is given -1 means a reverse string is returned.

Example

In this example, we are implementing string slicing.

string="includehelp is a portal to learn concepts"
print(string[3:7])
print(string[:7])
print(string[15:])
print(string[0::3])
print(string[7:3:-1])
print(string[::-1])

The output of the above example is:

lude
include
a portal to learn concepts
ileliaoatlrcct
hedu
stpecnoc nrael ot latrop a si plehedulcni

5. Python String Comparison (== and !=) Operators

To compare two strings, we use the comparison operators, the == returns true, if both strings are equal and the != returns true if both strings are not equal.

Example

This example demonstrates the use of comparison operators (== and !=).

str1 = "Hello"
str2 = "Hello"
str3 = "world!"

if str1 == str2:
    print("str1 and str2 are equal")
else:
    print("str1 and str2 are not equal")

if str1 != str3:
    print("str1 and str3 are not equal")
else:
    print("str1 and str3 are equal")

Output:

The output of the above example is:

str1 and str2 are equal
str1 and str3 are not equal

6. Python String Membership (in and not in) Operators

With Python strings, the in operator is used to check whether a substring exists in the string, and the not in operator is used to check whether a substring does not exist in the string.

Example 1

This example demonstrates the use of membership operators (in and not in).

str1 = "Coding"
print("n" in str1)
print("ing" not in str1)

str2 = "Hello, World!"
print("x" not in str2)
print("lo, " in str2)

Output:

The output of the above example is:

True
False
True
True

Example 2

# 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:

The output of the above example is:

'is' exists in IncludeHelp.com is very popular
'are' does not exist in IncludeHelp.com is very popular

7. Python String Escape Sequence (\) Operator

The escape sequence is the set of characters followed by a letter or a combination of digits starting with a backslash (\). For example, to print a new line - use \n, to print a double quote - use \", etc.

Example

This example demonstrates the use of escape sequence operator (\).

print("IncludeHelp\nLearn Python!")

# Tab escape sequence
print("IncludeHelp\tLearn Python!")

# Backslash escape sequence
print("This is a backslash: \\")

# Dounle quotes escape sequence
print('Hello, world. I am "IncludeHelp"')

Output:

The output of the above example is:

IncludeHelp
Learn Python!
IncludeHelp Learn Python!
This is a backslash: \
Hello, world. I am "IncludeHelp"

8. Python String Formatting (%, {}) Operators

The % is used as a format specifier to print specific values of the variable (like, %d for int, %c for character, %s for string, %f for float, etc.), and the {} is a placeholder that is used with the .format() method to print the parameter's value.

Example 1

This example demonstrates the use of format specifier %.

# Declaring variables
age = 21
height = 167.5
name = "Alex"

# Printing values using % (format specifier)
print("Name: %s, Age: %d, Height: %f" % (name, age, height))

Output:

The output of the above example is:

Name: Alex, Age: 21, Height: 167.500000

Example 2

This example demonstrates the use of placeholder {} with .format() method.

# Declaring two strings
age = 21
height = 167

# Formatting string
result = "My age is {} and my height is {} cm.".format(age, height)

# Printing result
print("Formatted string (result):", result)

# More examples

# The default order
result = "{} {} {}".format("Alex", age, height)
print("result:", result)

# The positional order (indexes in placeholders)
result = "{0} {1} {2}".format("Alex", age, height)
print("result:", result)

# Using keywords in placeholders
result = "{na} {ag} {hg}".format(na="Alex", ag=age, hg=height)
print("result:", result)

Output:

The output of the above example is:

Formatted string (result): My age is 21 and my height is 167 cm.
result: Alex 21 167
result: Alex 21 167
result: Alex 21 167

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.