WORKING WITH STRINGS
You can concatenate two strings using the “+” operator. The following example prints a string and then concatenates two single-letter strings:
>>> 'abc' 'abc' >>> 'a' + 'b' 'ab'
You can use “+” or “*” to concatenate identical strings, as shown here:
>>> 'a' + 'a' + 'a' 'aaa' >>> 'a' * 3 'aaa'
You can assign strings to variables and print them using the print() command:
>>> print('abc')
abc
>>> x = 'abc'
>>> print(x)
abc
>>> y = 'def'
>>> print(x + y)
abcdef
You can “unpack” the letters of a string and assign them to variables, as shown here:
>>> str = "World" >>> x1,x2,x3,x4,x5 = str >>> x1 'W' >>> x2 'o' >>> x3 'r' >>> x4 'l' >>> x5 'd'
The preceding code snippets show you how easy it is to extract the letters in a text string, and in Chapter 3 you will learn how to “unpack” other data structures.
You can extract substrings of a string as shown in the following examples:
>>> x = "abcdef" >>> x[0] 'a' >>> x[-1] 'f' >>> x[1:3] 'bc' >>> x[0:2] + x[5:] 'abf'
However, you will cause an error if you attempt to “subtract” two strings:
>>> 'a' - 'b' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for -: 'str' and 'str'
The try/except construct enables you to handle the preceding type of exception gracefully.
Comparing Strings
You can use the methods lower() and upper() to convert a string to lowercase and uppercase, respectively, as shown here:
>>> 'Python'.lower() 'python' >>> 'Python'.upper() 'PYTHON' >>>
The methods lower() and upper() are useful for performing a case-insensitive comparison of two ASCII strings. Listing 1.2 displays the content of compare.py that uses the lower() function to compare two ASCII strings.
LISTING 1.2: compare.py
x = 'Abc'
y = 'abc'
if(x == y):
print('x and y: identical')
elif (x.lower() == y.lower()):
print('x and y: case insensitive match')
else:
print('x and y: different')
Since x contains mixed case letters and y contains lowercase letters, Listing 1.2 displays the following output:
x and y: different
Formatting Strings
Python provides the functions string.lstring(), string.rstring(), and string.center() for positioning a text string so that it is left-justified, right-justified, and centered, respectively. As you saw in a previous section, Python also provides the format() method for advanced interpolation features.
Now enter the following commands in the interpreter:
import string str1 = 'this is a string' print(string.ljust(str1, 10)) print(string.rjust(str1, 40)) print(string.center(str1,40))
The output is shown here:
this is a string
this is a string
this is a string
The next portion of this chapter shows you how to “slice and dice” text strings with built-in functions.