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:
- Concatenation of two or more strings.
- Extracting or slicing partial strings from string values.
- Adding or removing spaces.
- Converting to lower or upper case.
- Formatting strings using string formatters.
- Finding and/or replacing a text in the given string with some other text.
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:
- Using f-strings
- By format() method
- 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()
- In default formatting {} will refer to the format() arguments in the order in which they are placed.
- In positional formatting order is indicated inside {}. Above example “{1} {2} {0}”.format(“love”, “Travelling”, “is”) states that argument positioned at index 1 (“travelling”) inside format() will come first, argument position at 2 index(“is”) will come second and argument positioned at index 0(“love”) will come last.
- In keyword formatting, certain keywords are used inside {} which will be mapped to corresponding format() arguments.
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:
- lower(): Converts a string to the lowercase letter.
- upper(): Converts a string to the uppercase letter.
- islower() / isupper(): Checks if the whole string is in lower case or upper case and returns bool value respectively.
- startswith(): Returns a bool value. Check if the given string starts with a particular text.
- endswith(): Returns a bool value. Check if the given string ends with a particular text.
- join(): Join different strings to make a single concatenated string. A list of strings is joined together into a single string.
- split(): Reverse of join(). It splits a large string into smaller strings. By default, a string is split wherever characters such as space, tab or newline characters are found. However, a delimiter can be passed inside the split(). The string then will split when this delimiter is encountered.
- ljust()/ rjust()/ center(): These three methods are for justifying text. The first argument is an integer length for the justified string, and the second argument is the fill character. ljust() fills the fill char on the left side, rjust() fills the fill char on the right side, and center() justifies the text at the center, filling the fill char at both left and right sides.
- strip()/ lstrip()/ strip(): Removes whitespaces(space, tab and newline) from left side(lstrip()), right side(rstrip()) and from both sides(strip()).
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:
- index(): index() method finds the first occurrence of a particular character or text in the given string. In this example, the index position for the first occurrence of ‘r’ is printed.
- count(): counts the total number of occurrences of a character in the given string. Character ‘o’ occurs thrice in the string “object-oriented programming.”
- find(): find() method is similar to index() method. It also returns the index for the first occurrence. But the major difference is that if a character whose index is to find is not present, index() will throw an error while find() returns -1 (as shown in the output)
- replace(): It replaces a text with another text in the given string. In this example, ‘e’ is being replaced by ‘3’.
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 –