Python String and how to use str(), Slicing and Joining, split(), Traversing

Python String


Python Strings are enclosed by either single or double quotation marks. To store a python string inside a variable, you just need to assign a string to a variable. In the above code, all the variables on the left side of the assignment operator are string variables. A single character is also treated as a string. A string does not need to have any characters in it. Both are valid strings, called empty strings. A string enclosed in double quotation marks can contain single quotation marks. Likewise, a string enclosed in single quotation marks can contain double quotation marks. So basically, if one type of quotation mark surrounds the string, you have to use the other type within it. If you want to include the same quotation marks within a string as you have used to enclose the string, then you need to preface the inner quote with a backslash. If you have a string spanning multiple lines, then it can be included within triple quotes. All white spaces and newlines used inside the triple quotes are literally reflected in the string _. You can find the type of a variable by passing it as an argument to type() function. Python strings are of the str data type.

The Python string str() Function:

The str() function returns a string which is considered an informal or nicely printable representation of the given object. The syntax for str() function is,


It returns a string version of the object. If the object is not provided, then it returns an empty string.

Here integer type is converted to string type. Notice the single quotes to represent the

string . The create_string is an empty string of type str.

Basic Python String Operations:

In Python, strings can also be concatenated using + sign and * operator is used to create a repeated sequence of strings.

Two string variables are assigned with “programming” and “digest”  string values. The string_1 and string_2 are concatenated using + operator to form a new python string. The new python string concatenated_string  has the values of both the strings. As you can see in the output, there is no space between the two concatenated string values. If you need whitespace between concatenated strings, all you need to do is include whitespace within a string like in. You cannot use the + operator to concatenate values of two different types. For example, you cannot concatenate a python string data type with the integer data type. You need to convert integer type to string type and then concatenate the values. You can use the multiplication operator * on a string _. It repeats the string the number of times you specify and the string value “programmingdigest” is repeated five times. You can check for the presence of a string in another string using in and not in membership operators. It returns either a Boolean True or False. The in operator evaluates to True if the string value in the left operand appears in the sequence of characters of a python string value in the right operand. The not in operator evaluates to True if the string value in the left operand does not appear in the sequence of characters of a python string value in the right operand.

Python cannot concatenate string value with integer value since they are of different data types. You need to convert integer type to string type before concatenating integer and string values. The statement returns True because the string “apple” is present in the string “apple is a fruit“. The not in operator evaluates to True as the string “orange” is not present in “apple is a fruit” string .

Python String Comparison

You can use (>, <, <=, >=, ==, !=) to compare two python strings resulting in either Boolean True or False value. Python compares strings using ASCII value of the characters. For example,

Strings can be compared using various comparison operators. python String equality is compared using == (double equal sign). python String inequality is compared using != sign. Suppose you have string_1 as “january” and string_2 as “jane”. The first two characters from string_1 and string_2 (j and j) are compared. As they are equal, the second two characters are compared (a and a). Because they are also equal, the third two characters (n and n) are compared. Since the third characters are also equal, the fourth character from both the python string is compared and because ‘u’ has greater ASCII value than ‘e’, string_1 is greater than string_2. You can even compare a string against an empty python string.

Accessing Characters in String by Index Number

Each character in the python string occupies a position in the string. Each of the string’s characters corresponds to an index number. The first character is at index 0; the next character is at index 1, and so on. The range of a string is the number of characters in it. You can access each character in a python string using a subscript operator i.e., a square bracket. Square brackets are used to perform indexing in a string to get the value at a specific index or position. This

is also called subscript operator. The index breakdown for the string “be yourself” assigned to word_phrase string variable is shown below.

b e y o u r s e l f

0 1 2 3 4 5 6 7 8 9 10 Index


The syntax for accessing an individual character in a string is as shown below.


where index is usually in the range of 0 to one less than the length of the string. The value of index should always be an integer and indicates the character to be accessed. For example,

By referring to the index numbers in a square bracket, you can access individual characters in a python string. The index number starts with zero correspondings to the first character in the python string. The index number increases by one as we move to access the next letter to the right of the current letter. The whitespace character between be and yourself has its own index number, i.e., 2. The last character in the string is referenced by an index value which is the (size of the string – 1) or (len(string) – 1). If you try to specify an index number more than the number of characters in the string, then it results in IndexError: string index out of range error. You can also access individual characters in a string using negative indexing. If you have a long string and want to access end characters in the string, then you can count backward from the end of the string starting from an index number of −1. The negative index breakdown for the string “be yourself” assigned to word_phrase string variable is shown below.

b e y o u r s e l f

-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1



By using a negative index number of −1, you can print the character ‘f’, the negative index number of −2 prints the character ‘l’. You can benefit from using negative indexing when you want to access characters at the end of a long string.

String Slicing and Joining

The “slice” syntax is a handy way to refer to sub-parts of a sequence of characters within an original string. The syntax for string slicing is,


The colon is used to specify range values With python string slicing, you can access a sequence of characters by specifying a range of index numbers separated by a colon. python String slicing returns a sequence of characters beginning at the start and extending up to but not including end. The start and end indexing values have to be integers. String slicing can be done using either positive or negative indexing.

g r e e n t e a

0 1 2 3 4 5 6 7 8



A substring is created when slicing the python strings, which is basically a string that already exists within another string. A substring is any arrangement of characters that are contained in a python string. The string “green tea” is assigned to healthy_drink variable and a sequence of characters or a substring is extracted from the beginning (0th Index) up to the third character(2nd Index). In python string slicing, start index value (including) is where slicing starts and end index value (excluding) is where the slicing ends. If the start index is omitted, the slicing starts from the first index number (0th Index) up to the end index (excluding) in the string. In substring starting from 0th index to 4th index is printed. If the end index is omitted, slicing starts from the start index and goes up to the end of the string index. Substring starting from 6th index to the end of the string is displayed in. If both the start and end index values are omitted then the entire string is displayed. If the start index is equal to or higher than the end index, then it results in an empty string. If the end index number is beyond the end of the string, it stops at the end of the string. Slicing can also be done using the negative integer numbers.

g r e e n t e a

-9 -8 -7 -6 -5 -4 -3 -2 -1

The negative index can be used to access individual characters in a string. Negative indexing starts with −1 index corresponding to the last character in the string and then the index decreases by one as we move to the left.

You need to specify the lowest negative integer number in the start index position when using negative index numbers as it occurs earlier in the string. You can also combine positive and negative indexing numbers.

Joining Strings Using  join() Method

python String can be joined with the join() string. The join() method provides a flexible way to concatenate strings. The syntax of join() method is, string_name.join(sequence) Here sequence can be string or list. If the sequence is a string, then join() function inserts string_name between each character of the string sequence and returns the concatenated string. If the sequence is a list, then join() function inserts string_name between each item of list sequence and returns the concatenated string. It should be noted that all the items in the list should be of string type.

All the items in the list date_of_birth list variable is of string type. In  the string “:” isinserted between each list item and the concatenated string is displayed. In social_app list variable, all the list items are of string type. In , the join() method ensures a blank space is inserted between each of the list items in social_app and the concatenated string is displayed. The variables numbers  and characters are of string type. The python string value of “123” is placed between each character of “amy” string resulting in ‘a123m123y’. The string value of “123” is inserted between a and m and again between m and y and is assigned to password string variable.

Strings Using split() Method

The split() method returns a list of string items by breaking up the string using the delimiter string. The syntax of split() method is,

string_name.split([separator [, maxsplit]])

Here separator is the delimiter string and is optional. A given string is split into list of strings based on the specified separator. If the separator is not specified then whitespace is considered as the delimiter string to separate the strings. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit + 1 items). If maxsplit is not stated or −1, then there is no limit on the number of splits.

The value in inventors string variable is separated based on “,” (comma) separator. In  no separator is specified in split() method. Hence, the string variable watches is separated based on whitespace.

String Traversing

Since the string is a sequence of characters, each of these characters can be traversed using the for loop.

Example: Program to Demonstrate String Traversing Using the for Loop

python String value “google” is assigned to alphabet string variable and index variable is initialized to zero. The for statement makes it easy to loop over each character in a string. For each character traversed in the python string, the index value is incremented by a value of one. Each character in the string and its corresponding index value is printed in .

Example: Program to Print the Characters Which Are Common in Two Strings

Two python string values, ‘rose‘ and ‘goose, are passed as arguments to common_characters() function. The string values ‘rose‘ and ‘goose‘ are assigned to string_1 and string_2 parameter variables. A for loop is used to traverse through each letter in the python string value assigned to string_1 parameter variable. If any of the letter is found in string_2 parameter variable then that character is printed out.

Example: Write Python Program to Count the Total Number of Vowels, Consonants and Blanks in a String

User entered string is assigned to a user_string  variable. Initially, zero is assigned to vowels, consonants and blanks variables. Each of the characters in user_string is traversed using for loop . If the character traversed in user entered string matches with any of the vowels then the vowels variable is incremented by one. If the character traversed is not a vowel then it is treated as consonant and the consonants variable is incremented by one –_. Also, characters are checked for ” ” (blank space) . If yes, then the blanks variable is incremented by one . The syntax “a” < each_character < “z” is a shorthand syntax equivalent to each_character > “a” and each_character < “z”. This shorthand syntax is called “chain comparison operation.” This “chain comparison operation” is possible as all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation and the comparison operation yields either Boolean True or False.

Example: Write Python Program to Calculate the Length of a String Without Using Built-In len() Function

User entered string is assigned to user_string variable. The count_character variable is assigned to zero value. The count_character acts like a counter which keeps track of a number of characters and gets incremented by a value of one when the user_string is traversed using for loop.

Reversing a string

A string can reversed using the built-in reversed() function, which takes a string and returns an iterator in reverse order.

reversed() can be wrapped in a call to ”.join() to make a python string from the iterator.

While using reversed() might be more readable to uninitiated Python users, using extended slicing with a step of -1 is faster and more concise. Here , try to implement it as function:


Related Projects:

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button