A sequence of characters is known as a string. Python allows you to use single quotes (‘), double quotes (“) or triple quotes (“””) to denote a string.
String methods
Python allows you to perform several string operations using some predefined string functions.
1) len() length
The len() method is used to find the length of a string.
a = "Hello World!"
print(len(a))
# Output
# 12
2) strip() function
The strip() method is used to remove white-space from the beginning and end of a string.
name = " John Doe "
print(name.strip())
# Output
# John Doe
3) split() method
Python’s split() method function is used to break down the string into an array of smaller strings knows as substrings using a defined separator. If you donot specify a separator, whitespace will be considered as the separator.
Example 1
names = "John, Joe, Janet"
print(names.split(','))
print(names.split())
a="Let's learn python"
print(a.split('learn'))
# Output
# ['John', ' Joe', ' Janet']['John,', 'Joe,', 'Janet']["Let's ", ' python']
Example 2 – Assigning values to separate variables
names = "John, Joe, Janet"
a,b,c = names.split(',')
print(a)
print(b)
print(c)
# Output
# John
# Joe
# Janet
4) capitalize() method
Python capitalize method converts the first letter of the specified string to uppercase and the remaining part of the string to lowercase.
Example
a="python is an interpreted high-level PROGRAMMING LANGUAGE."
b=a.capitalize()
print(b)
c="this is an ExamplE of capitalize function.".capitalize()
print(c)
# Output
# Python is an interpreted high-level programming language
# This is an example of capitalize function
5) upper() method
This method converts the given string to uppercase.
Example
a="python is an interpreted high-level PROGRAMMING LANGUAGE."
print(a.upper())
print("hello World".upper())
# Output
# PYTHON IS AN INTERPRETED HIGH-LEVEL PROGRAMMING LANGUAGE.
# HELLO WORLD
6) lower() method
This method converts the given string to lowercase.
a="Python is an interpreted high-level PROGRAMMING LANGUAGE."
print(a.lower())
print("HELLO world".lower())
# Output
# python is an interpreted high-level programming language.
# hello world
7) replace() method
The replace() method replaces all the occurrence of a substring with another substring. This method takes two parameters:
- Substring to replace.
- Substring to replace with.
Example
a="PHP is an interpreted high-level programming language."
print(a.replace('PHP','Python'))
# Output
# Python is an interpreted high-level programming language.