Python String Methods

Strings are immutable sequences of characters, and Python offers various algorithms for efficiently processing them, encompassing tasks like searching, sorting, comparing, and transforming. When creating a string, enclose the sequence of characters within single quotes, double quotes, or triple quotes and then assign it to a variable. The immutability of strings implies that once created, their contents cannot be altered.

str = 'Hellow World!' str = "Hellow World!" str = """Sunday Monday Tuesday"""

Access characters in a string

You can access individual characters from a string using square brackets []. The index inside the brackets represents the position of the character you want to access. Python uses 0-based indexing, which means the first character of the string is at index 0, the second character at index 1, and so on.

str = 'Hellow World!' print(str [0]) # output is "H" print(str [7]) # output is "W" print(str [0:6]) #output is Hellow print(str [7:12]) #output is World

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

print(str [0:-6]) # output is Hellow print(str [7:-1]) # output is World

String Concatenation

Concatenation is the process of combining two or more strings into a single unified string. In Python, this merging operation is achieved using the "+" operator, which allows the joining of one or more strings to create a new concatenated string.

str1 = 'Hellow ' str2 = ' World!' print(str1 + str2) #Output: Hellow World!

Reverse a String

Strings are sliceable, meaning you can extract a portion of a string to create a new string. Slicing allows you to obtain a substring by specifying a start and end position, along with an optional step size, to control the increments. Slicing can be achieved using either slice notation or a slice object within square brackets.

string[subscript]

The subscript creates a slice by including a colon within the braces:

string[begin:end:step]

It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

str = 'Python String' print(str[::-1]) #Output:gnirtS nohtyP

String Methods

The string data type comes with a variety of built-in methods that enable convenient modification and manipulation of strings. These methods, known as built-in methods, are inherent to the Python programming language, readily accessible for seamless utilization in our code. By using these methods, programmers can efficiently perform tasks like string concatenation, case conversions, searching, replacing, and many other text-related operations.

Python String len() method

The len() method in Python is used to determine the length of a given string. It returns the number of characters present in the string, providing valuable information about the size of the string data.

str = "Hellow World!" print(len(str)) #Output:13

Python String count() method

The count() method in Python is used to count the number of occurrences of a specified substring within the given string. It returns the total count of how many times the substring appears in the original string, providing useful information about the frequency of a particular sequence of characters.

str = "Python is Object Oriented" substr = "Object" print(str.count(substr)) # return 1, becasue the word Object exist 1 time in str #Output:1

Python String index() method

The index() method in Python is used to find the index (position) of the first occurrence of a specified substring within the given string. It returns the index value where the substring is found, providing the position of the first occurrence of the substring in the original string. If the substring is not found, it raises a ValueError.

index(substr,start,end)

end(optional) by default its equal to the length of the string.

str = "Python is Object Oriented" substr = "is" print(str.index(substr)) #Output:7

Python String upper() method

The upper() method in Python is used to convert the characters in the given string to uppercase letters and returns a new string with all uppercase characters. The original string remains unchanged, and the upper() method provides an easy way to transform the text to uppercase for further processing or display purposes.

str = "Python is Object Oriented" print(str.upper()) #Output:PYTHON IS OBJECT ORIENTED

Python String lower() method

The lower() method in Python is used to convert the characters in the given string to lowercase letters and returns a new string with all lowercase characters. The original string remains unchanged, and the lower() method provides a convenient way to transform the text to lowercase for further processing or display purposes.

str = "Python is Object Oriented" print(str.lower()) #Output:python is object oriented

Python String startswith() method

The startswith() method in Python is used to check whether a string starts with the specified substring. It returns a Boolean value of True if the string begins with the given substring, and False otherwise. This method is useful for conditional checks to determine the presence of a specific pattern at the beginning of a string.

str = "Python is Object Oriented" print(str.startswith("Python")) print(str.startswith("Object")) #Output: True False

Python String endswith() method

The endswith() method returns a Boolean value of TRUE if the string ends with the specified substring; otherwise, it will return False.

str = "Python is Object Oriented" print(str.endswith("Oriented")) print(str.endswith("Object")) #Output: True False

Python String split() method

The split() method for strings breaks up a given string into smaller substrings based on a specified delimiter or character.

str = 'Python is Object Oriented' print(str.split()) #Output:['Python', 'is', 'Object', 'Oriented']
example
str = 'Python,is,Object,Oriented' print(str.split(',')) #Output:['Python', 'is', 'Object', 'Oriented']
example
str = 'Python,is,Object,Oriented' print(str.split(',',2)) #Output:['Python', 'is', 'Object,Oriented']

Python returned split string as a List

str = 'Python,is,Object,Oriented' sList = str.split(',') for temp in sList: print (temp) #Output: Python is Object Oriented

Python String join() method

The join() method for strings is a function that returns a new string by concatenating the elements of an iterable together.

str = "Python is Object Oriented" tmp = "-" print (tmp.join(str)) #Output:P-y-t-h-o-n- -i-s- -O-b-j-e-c-t- -O-r-i-e-n-t-e-d

Python String find() method

The find() method for strings returns the index position of the first occurrence of a specified substring. If the specified substring is not found, it will return -1.

str = "Python is Object Oriented" st = "Object" print (str.find(st)) print (str.find(st,20)) #finding from 20th position #Output: 10 -1

Python String strip() method

The strip() method for strings removes the specified characters from both the right-hand side and left-hand side of a string, by default, it removes white spaces, and then returns the new string.

str = " Python is Object Oriented " print (str.strip()) #Output:Python is Object Oriented

Python String rstrip() method

The rstrip() method for strings returns a new string with trailing characters removed. Trailing characters refer to the characters at the right-hand side (end) of the string that match the provided argument.

str = " Python is Object Oriented " print (str.rstrip()) #Output:Python is Object Oriented

Python String lstrip() method

The lstrip() method for strings returns a new string with leading characters removed. Leading characters refer to the characters at the left-hand side (beginning) of the string that match the provided argument.

str = " Python is Object Oriented " print (str.lstrip()) #Output:Python is Object Oriented

Conclusion

String manipulation in Python involves performing operations on strings, such as concatenation, slicing, finding substrings, and converting cases. Python's built-in string methods like split(), strip(), and join() offer powerful ways to manipulate and transform strings for various data processing tasks.