Strings

In Python, a string is a variable type that stores text characters such as letters, numbers, special characters, and punctuation. In Python, we use single or double quotation marks to indicate that the variable is a string rather than a number:

var = 'Hello, World!'
print(var)

Strings cannot be used for mathematical operations on numbers. But they can be used for other useful operations, as we see in the following example:

string_1 = '1'
string_2 = '2'
string_sum = string_1 + string_2
print(string_sum)

The result of the preceding code is to print string '12', not '3'. Instead of adding the two numbers, the + operator performs concatenation (appending the second string to the end of the first string) in Python when operating on two strings.

Other operators that act on strings include the * operator (for repeating strings number of times, for example, string_1 * 3) and the < and > operators (to compare the ASCII values of the strings).

To convert data from a numeric type to a string, we can use the str() method.

Because strings are sequences (of characters), we can index them and slice them (like we can do with other data containers, as you will see later). A slice is a contiguous section of a string. To index/slice them, we use integers enclosed in square brackets to indicate the character's position:

test_string = 'Healthcare'
print(test_string[0])

The output is shown as follows:

H

To slice strings, we include the beginning and end positions, separated by a colon, in the square brackets. Note that the end position will include all the characters up to but not including the end position, as we see in the following example:

print(test_string[0:6])

The output is as follows:

Health

Earlier, we mentioned the str() method. There are dozens of other methods for strings. A full list of them is available in the online Python documentation at www.python.org. Methods include those for case conversion, finding specific substrings, and stripping whitespace. We'll discuss one more method herethe split() method. The split() method acts on a string and takes a separator argument.

The output is a list of strings; each item in the list is a component of the original string, split by separator. This is very useful for parsing strings that are delimited by punctuation characters such as , or ;. We will discuss lists in the next section. Here is an example of the split() method:

test_split_string = 'Jones,Bill,49,Atlanta,GA,12345'
output = test_split_string.split(',')
print(output)

The output is as follows:

['Jones', 'Bill', '49', 'Atlanta', 'GA', '12345']
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset