Skip to main content

Python Common String Operations










A string is most popular type in Python. A string can be created by enclosing a sequence of characters in a single or double quotes (' ' or " "). A string module contains a number of powerful methods/function to perform operations on a string.

NOTE: string in Python is IMMUTABLE (it cannot be changed of the string) as in many other languages (Java).
  1. Length of a string
  2. Range slice
  3. Accessing a character of a string
  4. Converting all string characters to all uppercase letters
  5. Converting all string characters to all lowercase letters
  6. Capitalizing string
  7. String concatenation
  8. Fining the index where the sub-string begins/occurs in a string 
  9. Check if string contains sub-string
  10. String comparison (Equality, less than, greater than, not equal)
  11. Breaking a string by ",", "-","  " (space), etc.                                                      

#Let's start by declaring a string

#a string object is created and assigned "Python is an incredibly powerful language." 
string  = "Python is an incredibly powerful language."

print(string)#Output:Python is an incredibly powerful language.


The same string is used through out this article for demonstration purpose.

1. len() - Length of a string can be could be found using built-in function: len( Object )
- Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).


length = len(string)
print(length) #Output: 42 

2. A string can be sliced using brackets [] operator string[I:J],  sliced from I to J-1

print(string[0:6])#Output:Python

#equivalent to
##[:J] everything excluding J

print(string[:6]) #Output:Python 
print(string[:-35]) #Output:Python



print(string[7:len(string)]) #Output:is an incredibly powerful language.

#equivalent to
#[I:] everything including I

print(string[7:]) #Output:is an incredibly powerful language.


#printing string the hardway
print(string[:])#output:Python is an incredibly powerful language.



3. To access character of a string string[index]
 
print(string[0]) #Output:P
print(string[5]) #output:n

4.upper() - Return a copy of the string with all the cased characters [4] converted to uppercase. Note that str.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, title case).


#Converting all characters of a string to uppercase

print(string.upper())#Output:PYTHON IS AN INCREDIBLY POWERFUL LANGUAGE.


5.lower() -  Return a copy of the string with all the cased characters converted to lowercase.

#5.Converting all characters of a string to lowercase

print(string.lower())#Output:python is an incredibly powerful language.

6. capitalize()- Return a copy of the string with its first character capitalized and the rest lowercase.


#6.Capitalize only the first character of the string

string = "python is an incredibly powerful language."
print(string.capitalize())#Output:Python is an incredibly powerful language.


7. Concatenation- strings can be appended using a  "+" operator

#7.Concatenation

string1 = "Python "
string2 = "is "
string3 = "incredibly "
string4 = "powerful "
string5 = "language."

string = ""
string = string+string1

print(string)#Output:Python

string+=string2+string3+string4+string5

print(string)#Output:Python is an incredibly powerful language.

8. find( ) - Return the lowest index in the string where sub-string sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

print(string.find('Python')) #Output:0
print(string.find('an')) #Output:31


9. in - The in operator in python tests the membership. For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True. There is not in operator which is basically negation of in operator.

#9. in and not in operator

print('Python' in string)     #Output:True
print('Python' not in string) #Output:False
print('Py' in string)         #Output:True
print('incredibly' in string) #Output:True

10.String comparison - In python, strings can be compared using relational operator (<,<=,>=,>,==,!=)  just like comparing two entities(e.g., 10 == 10). Python does the comparison using lexicographical comparison (using the ASCII value of character).

 
#String comparison

string1 = "blogspot.com"
string2 = "blogspot.com"
string3 = "blogspot"
string4 = "com"

print("blogspot.com == blogspot.com?", string1 == string2) #Output: True
print("blogspot.com >= blogspot?", string2 >= string3)     #Output: True
print("blogspot.com < blogspot?",string2<string3)          #Output: False
print("blogspot     >= com?", string3 >= string4)          #Output: False
print("blogspot     > com?",string3>string4)               #Output: False
print("com         != blogspot.com?",string4!=string1)     #Output: True



11.split(sep = delimiter, maxsplit =-1 ) - Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

NOTE: If no sep is specified runs of consecutive white-space are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing white-space.

string  = "Python is an incredibly powerful language."
string1 = "Python-is-an-incredibly-powerful-language."
string2 = "P,y,t,h,o,n"

print(string.split()) 
 #Output:['Python', 'is', 'an', 'incredibly', 'powerful', 'language.']
print(string1.split('-'))  
#Output:['Python', 'is', 'an', 'incredibly', 'powerful', 'language.']
print(string2.split(',')) #Output:['P', 'y', 't', 'h', 'o', 'n']

Source: Python

Comments

Post a Comment

Popular posts from this blog

RLE Encoding and Decoding in C++

Given an input string, write a regular recursive function that returns the decoded (uncompresseed form) Run Length Encoded   (is a simple form of data compression where repeated character are replaced by count followed by the character repeated) string for the input string. Below are some examples: decode("*") =>* decode("3+") =>+++ decode("11*") =>*********** decode("101+") =>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ decode("abcde10+10*10+10x") =>abcde++++++++++**********++++++++++xxxxxxxxxx decode("\\") =>\ decode("\1\2\3") =>123 decode("13\7x") =>7777777777777x decode("5\\") =>\\\\\ decode("4\12\23\3") =>111122333 decode("4\\2\3") =>\\\\33 NOTE: To represent a single backslash, it’s necessary to place double backslashes (\\) in the input string to obtain the desired in

Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7    Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7   Note: The merging process must start from the root nodes of both trees.  Source: LeetCode Solution: We traverse both trees in a preorder fashion. In

Invert Binary Search Tree

Invert a binary tree. Example: 4 / \ 2 7 / \ / \ 1 3 6 9   to   4 / \ 7 2 / \ / \ 9 6 3 1  4 / \ 2 7 / \ / \ 1 3 6 9   Trees are crucial data structure in Computer Science. Often trees related problems are solved using recursion as it provides an elegant solution in this particular problem at least. The basic terminology to solve this problem is to swap the left and right values, if you work on the tree from the bottom the to the top swapping the left and right node, the tree will be inverted. Let's go through an example: You can start from left or right. So, starting from the left we have   2 2 (swap the left and right node) / \ => / \ 1 3 3 1   7 7 (similarly, on the right sub-tree) / \ => / \ 6 9 9 6    Which gives,   4 / \ 2 7 / \ / \ 3 1 9 6 And finally, 4 (swap ag