[proxy] web.archive.org← back | site home | direct (HTTPS) ↗ | proxy home | ◑ dark◐ light

Python String Operations | Different Methods to Perform String Operations

Introduction to Python String Operations

A Python String is a sequence of characters. Python Strings are immutable, it means once we declare a string, we can’t modify it. Python provides a built-in class “str” for handling text as the text is the most common form of data that a Python program handles. Following are the common string operations that can be performed in Python:

And the list of operations is countless. Python provides several built-in methods that let us to perform operations on a string in a flexible way.

Examples of String Operations in Python

String Operations can be done in three ways:

  1. Using f-strings
  2. By format() method
  3. Using % operator

Example #1

# String formatters in Python
# String formatting using f-strings
print("")
print("Enter your name")
name = input()
print(f"Hey !! {name}, welcome to the party...")
print('\n')
print("")
print("Enter first number")
a = int(input())
print("Enter second number")
b = int(input())
print(f"sum of {a} and {b} is {a+b}")
print('\n')
# String formatting using format() method
print("")
str1 = "{} {} {}".format("Travelling", 'is', 'life')
print("String will be printed in
default order:")
print(str1)
print("")
str2 = "{1} {2} {0}".format("love", "Travelling", "is")
print(str2)
print("")
str3 = "{T} {i} {l}".format(T='Travelling', l='love', i='is')
print(str3)
print('\n')
# String formatting using % operator
print("Enter number of items")
item = int(input())
print("%s is carrying %d items"%(name, item))

Output:

Explanation:

1. f-string: Letter “f” is placed before the beginning of the string, and the variables mentioned in curly braces will refer to the variables declared above. For example, {name} refers to the name variable defined above. Similarly {a} and {b} refers to variable a and b respectively.

2. format() method: format() method is called on a string object. Inside the string, we use curly braces {} that will refer to the format() method arguments. Number of {} should match the number of arguments inside format()

3. % operator: “%” operator will be replaced by variables defined in parenthesis/in tuple. %s means a string variable will come to this place, %d is an integer, %f is a floating-point value.

Example #2

# String methods Part 1
string = "Various string methods"
string2 = " investment in learning "
print("lower()")
print(string.lower())
print("upper()")
print(string.upper())
print("islower()")
print(string.islower())
print("isupper()")
print(string.isupper())
print("startswith")
print(string.startswith("Var"))
print("endswith()")
print(string.endswith("el"))
print("join()")
print('-->'.join(['various', 'strings', 'methods']))
print("split()")
print(string.split())
print("ljust()")
print("hello".ljust(15, '*'))
print("rjust(*)")
print("hello".rjust(15, '*'))
print("center()")
print("welcome".center(20, '*'))
print("strip()>")
print(string2.strip())
print("lstrip()")
print(string2.lstrip())
print("rstrip()")
print(string2.rstrip())

Output:

Explanation:

Example #3

# String methods--> Part 2
string = "object oriented programming"
print("Given string :", string)
print('index()')
print("index of 'r' in:'", string, "':", string.index('r'))
print('count()')
print("number of 'o' in '", string, "':", string.count('o'))
print('find()')
print("index of 'z'in '", string, "':", string.find('z'))
print('replace()')
print("replacing 'e' with '3' :", string.replace('e', '3'))

Output:

Explanation:

Conclusion

Text is the most common form of data a Python program has to operate on. Therefore, Python provides a comprehensive list of string methods that helps the user to perform various operations on strings (bits of text) in a much flexible way without writing the bulk of code.

Recommended Articles

This is a guide to Python String Operations. Here we discuss the different string methods to perform various operations on a string in python, along with an example and its code implementation. You can also go through our other related articles to learn more –

  1. Python Compare Strings
  2. Python List Functions
  3. Python Trim String
  4. Python Generators