In this article, we are going to discuss operations on strings. As we know in python, a string is an immutable data type (read-only). This can be declared in single quotes (s=’ ’) or double quotes (s=” ”), or triple quotes (s=’’’ ’’’ or s=””” “””)
How to enter into the python interpreter
Open Linux terminal and type python and hit enter so we will see python interpreter. For python3+ version, type python3. The following info we are going to see on the terminal. If we want to check the python version, the command is “python -v.”
Output:
[GCC 5.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
The following operations can be performed on the string
String Slice
This is useful when we want only part of the string.
Note: string index always starts from 0. A string can be traversed in forward and as well as reverse direction (using the negative index).
Ex: s =”Good morning”
reverse traverse index :[..,-3,-2,-1] here s[-1]=”g”, s[-2]=”n”, s[-3]=”I”,…
syntax: variablename[start:stop:step].
Here stop is excluded. If we provide only a start, it will extract all the characters from start to end. If we provide only a stop, it will extract from the 0th index to stop. We can omit both starts and stop; in that case, we need to provide at least colon (s[:]). If we don’t provide a Step value, the default value is 1.
Ex: s1 = ”Good morning”.
In this example, we want to extract “good”.
Suppose we want to extract “ood mor”
Suppose we want to extract “ning”(using the reverse index)
Suppose we want to reverse a string
Length
This method returns the number of characters in the string.
syntax: len(string)
Concatenation
This concatenates or combines two strings.
syntax: s3 = s1 + s2
Uppercase
This method converts all the characters in the string to upper case.
syntax: string.upper()
s2 = s1.upper()
Lowercase
This method converts all the characters in the string to lower case.
syntax: string.lower()
s2 = s1.lower()
Strip
This method strip/delete the value from the string provided as a parameter. The default parameter is space.
There 3 types of strips:
- lstrip() : This strips only the left side of the string.
- rstrip() : This strips only the right side of the string.
- strip() : This strips entire string.
Search substring in a string
This return “True” if substring found in string else returns False. The membership operators “in” and “not in” is used to check this.
syntax: substring in a string
Startswith
This method is used to check if a string starts with a substring. It returns True if the string starts with substring else return False.
syntax: s.starsiwth(substring)
Endswith
This method is used to check if a string ends with a substring. It returns “True” if the string ends with substring else return False
syntax: s.endsiwth(substring)
Index
This method is used to find the index of the substring in a string. If found, returns start character index of substring else value error exception is raised.
syntax: string.index(substing, beg=0,end=len(string))
Find
This method is used to find the index of a substring in a string. If found, returns start character index of substring else -1 value returned.
syntax: string.find(substing, beg=0,end=len(string))
Count
This method is used to count the occurrence of a substring in a string.
syntax: string.count(substring)
Swap case
This method swap/interchange the case of a string.
syntax: string. Swapcase()
Capitalize
This method capitalizes the first letter of string
syntax: string.capitalize()
Find minimum/maximum alphabetical character in the string
syntax: min(string), max(string)
Replace
This method replaces the occurrence of a substring with another string. If max provided that many times it will replace
syntax: string. replace (old substring, newstring, max)
Split
This method Split the string based on the parameter provided. It returns a list of words if a split parameter found other returns string as a list.
In 1st example, the split character is space, and it is found in a string. It returns a list of words
In 2nd example, the split character is _, and it did not found in the string. It returns the same string as the list.
Check string contain alphanumeric characters
This method returns “True” if all characters in a string are alphanumeric; otherwise, False
syntax: string.isalnum()
Check string contains alphabetic characters
This method returns “True” if all characters in a string are alphabetic; otherwise, False
syntax: string.isalpha()
Check string contains only digits
This method returns “True” if all characters in a string are digits; otherwise, False
syntax: string.isdigit()
Check string contain all lowercase characters
This method returns “True” if all characters in a string are lowercase; otherwise, False
syntax: string.islower()
Check string contain all uppercase characters
This method returns “True” if all characters in a string are uppercase; otherwise, False
syntax: string.isupper()
Check string contains only space
This method returns “True” if all characters in a string are spaces; otherwise, False
syntax: string.isspace()
Join
This method takes all items in a sequence (list, tuple, dict) and joins as a single string based on parameter. All items should be a string.
syntax: parameter.join(sequence)
Here the sequence is a list, and all items are joined using space and # parameter.
Conclusion
The string is an immutable datatype, and any operation we perform should be stored in another string variable. The above are the most common and generally used operation on string.
If we want to check what are all operations are supported for string type dir(str) on an interpreter and hit enter. It will display all methods/functions if we want to check the documentation for string method/function type help(str) and hit enter.