Python Programming – Python Strings
The collection or sequence of characters is called a string. As Python list contain a sequence of heterogeneous data elements, the string contains a contiguous sequence of characters, which can be alphabets or special characters. We know that computer understands only binary data either 0 or 1. All the data that we type and use in the computer is first converted into binary form. Therefore, the strings that are alphabetical or character data is also converted into equivalent binary code using some encoding technique such as ASCII or Unicode encoding. In Python, Unicode encoding is used for strings. The Unicode encoding is used to bring uniformity as it includes all the characters of all the languages. The string is a useful data element of Python as it is used to store character values such as name, city, class, etc.
Creating a String in Python
The creation of string is rather simple in Python. The programmer does not need to specify the string size as in C, C++, and Java. The programmer can create a string of any size. The programming illustration of creating a string is given in Code 5.44. In this program, three strings are created with names new_stringl, new_string2, and new_string3. In the first string, the value ‘Python’ is assigned in single quotes. In the second string, the value “Python” is assigned in double-quotes and in the last one triple quotes are used to assign the value. Thus, a string value can be provided in either single, double, or triple quotes.
Code: 5.44, Illustration of creating a string.
|#Illustration of creating a string
new_string 1 – ‘Python”
Accessing String Characters
Since the string is a sequence of characters, then string characters can be accessed by using the index operator or the slicing operator. A similar method is used that we have performed for lists and tuples. The programming illustration for the same is given in Code 5.45. In the program, it is clear that the particular character of a string can be accessed by specifying its index. The indexing starts from 0. Negative indexing is also possible, which is used to access elements from the end of the string. In the example, the slicing operator [:] is also used to print the string characters up to a certain range by excluding the last specified index value. The last character of the string represented by -1 indicates ‘n’ in Python string. -2 indicates ‘o’, -3 represents ‘h’, and so on.
Code: 5.45. Illustration of accessing string characters.
|#illustration of accessing a string
Changing or Deleting String Characters
Similar to a tuple, the string characters are also immutable. That means we cannot change or add elements to an existing string. However, the complete string can be deleted by using the del keyword. The programming illustration for the same is given in Code 5.46. In this example, we see that changing the character at index location  raises an error ‘str’ object does not support item assignment. Then print(new_string) statement also raises an error as del new_string has deleted the string and new_string does not exist.
Code: 5.46. Illustration of deleting a string.
|#illustration of changing/deleting a string
Python String Operations
The concatenation operation is used for adding two strings. This can be achieved by using the “+’ operator between two strings. In Python, the operator can also be used to repeat a particular string a specified number of times. The demonstration of both ‘+’ and ‘*5 operators is given in Code 5.47. As described, the *+’ operator has concatenated two strings strings 1 and string 2 and the operator has repeated the string! three times. The output can be referred to for more clarity of the concept.
Code: 5.47. Illustration of using ‘+’ and ‘*’ operators with string.
|#illustration of using ‘+’ and operators with string
print(string1 * 3)
Hello Welcome to Python Programming
Iteration and Membership Test
Since the string is a sequence of characters, the string can be iterated by using for loop as shown in Code 5.48. In this program, a string is created with value ‘Python Programming’. The values of all the string characters are accessed
by using for loop. As performed for list, tuple, and set, in the previous sections, the presence of a string member can be determined using ‘in’ operator. This is also illustrated in the programming code, which results in false for ‘p’ membership test. This is because the string1 contains capital letter ‘P’ and not the small one. Subsequently, the test for character’s comes out to be true.
Code: 5,48. Accessing string characters using for loop.
|#illustration of using for loop with string
string 1-Python Programming’
print(‘p’ in stringl)
A string can be formatted by using escape sequences and format symbols. The escape sequences are nonprintable characters that provide a good display for the output. These are used with a backslash. The Python string escape sequences are listed in Table 5.12.
|\r||ASCII Carriage Return|
|\t||ASCII Horizontal Tab|
|\v||ASCII Vertical Tab|
|\ooo||Character with octal value ooo|
|\xHH||Character with hexadecimal value HH|
The format symbols are already explained in Chapter 2 under Section 2.10.2.
Python String Built-in Methods
The Python language provides a list of methods to manipulate strings. The methods are listed in Table 5.13. These string methods are very easy to use by using the dot operator with the string name. For example the string length is determined as print(string.len()). This statement prints the length of the string, i.e., the total number of characters of the string1.
|len(string)||Returns the length of the string|
|max(str)||Returns the max alphabetical character from the string str.|
|min(str)||Returns the max alphabetical character from the string str.|
|Upper( )||Returns the min alphabetical character from the string str.|
|lower()||Converts lowercase letters in string to uppercase.|
|Capitalize ( )||Capitalizes first letter of string|
|center( width, fillchar)||Returns a space-padded string with the original string centered to a total of width columns.|
|isdigit()||Returns true if string contains only digits and false otherwise.|
|isalpha()||Returns true if string has at least one character and all characters are alphabetic and false otherwise.|
|isalnum()||Returns true if string has at least one character and all characters are alphanumeric and false otherwise.|
|islower()||Returns true if string has at least one cased character and all cased characters are in lowercase and false otherwise.|
|isupper()||Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.|
|Count( str, beg=0, end=len(string))||Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.|
|index(str, beg=0, end=len(string))||Same as find(), but raises an exception if str not found.|
|istitle()||Returns true if string is properly “titlecased” and false otherwise.|
|isnumeric()||Returns true if a Unicode string contains only numeric characters and false otherwise.|
|Swapcase( )||Inverts case for all letters in string.|
|title()||Returns “titlecased” version of string, that is, all words’ begin with uppercase and the rest are lowercase.|
|isdetimal( )||Returns true if a Unicode string contains only decimal characters and false otherwise.|
|Isspace( )||Returns true if string contains only whitespace characters and false otherwise.|