0% found this document useful (0 votes)
8 views

String Conversion Tools

Uploaded by

ram419906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

String Conversion Tools

Uploaded by

ram419906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

String Conversion Tools One of Python’s design mottos is that it refuses the temptation to guess.

As a
prime example, you cannot add a number and a string together in Python, even if the string looks like a
number (i.e., is all digits): >>> "42" + 1 TypeError: cannot concatenate 'str' and 'int' objects This is by
design: because + can mean both addition and concatenation, the choice of conversion would be
ambiguous. So, Python treats this as an error. In Python, magic is generally omitted if it will make your
life more complex. What to do, then, if your script obtains a number as a text string from a file or user
interface? The trick is that you need to employ conversion tools before you can treat a string like a
number, or vice versa. For instance: >>> int("42"), str(42) # Convert from/to string (42, '42') >>> repr(42)
# Convert to as-code string '42' The int function converts a string to a number, and the str function
converts a number to its string representation (essentially, what it looks like when printed). The repr
function (and the older backquotes expression, removed in Python 3.0) also converts an object to its
string representation, but returns the object as a string of code that can be rerun to recreate the object.
For strings, the result has quotes around it if displayed with a print statement: >>> print(str('spam'),
repr('spam')) ('spam', "'spam'") See the sidebar “str and repr Display Formats” on page 116 for more on
this topic. Of these, int and str are the generally prescribed conversion techniques. Now, although you
can’t mix strings and number types around operators such as +, you can manually convert operands
before that operation if needed: >>> S = "42" >>> I = 1 >>> S + I TypeError: cannot concatenate 'str' and
'int' objects >>> int(S) + I # Force addition 43 Strings in Action | 169 >>> S + str(I) # Force concatenation
'421' Similar built-in functions handle floating-point number conversions to and from strings: >>>
str(3.1415), float("1.5") ('3.1415', 1.5) >>> text = "1.234E-10" >>> float(text) 1.2340000000000001e-010
Later, we’ll further study the built-in eval function; it runs a string containing Python expression code
and so can convert a string to any kind of object. The functions int and float convert only to numbers,
but this restriction means they are usually faster (and more secure, because they do not accept arbitrary
expression code). As we saw briefly in Chapter 5, the string formatting expression also provides a way to
convert numbers to strings. We’ll discuss formatting further later in this chapter. Character code
conversions On the subject of conversions, it is also possible to convert a single character to its
underlying ASCII integer code by passing it to the built-in ord function—this returns the actual binary
value of the corresponding byte in memory. The chr function performs the inverse operation, taking an
ASCII integer code and converting it to the corresponding character: >>> ord('s') 115 >>> chr(115) 's' You
can use a loop to apply these functions to all characters in a string. These tools can also be used to
perform a sort of string-based math. To advance to the next character, for example, convert and do the
math in integer: >>> S = '5' >>> S = chr(ord(S) + 1) >>> S '6' >>> S = chr(ord(S) + 1) >>> S '7' At least for
single-character strings, this provides an alternative to using the built-in int function to convert from
string to integer: >>> int('5') 5 >>> ord('5') - ord('0') 5 170 | Chapter 7: Strings Such conversions can be
used in conjunction with looping statements, introduced in Chapter 4 and covered in depth in the next
part of this book, to convert a string of binary digits to their corresponding integer values. Each time
through the loop, multiply the current value by 2 and add the next digit’s integer value: >>> B = '1101' #
Convert binary digits to integer with ord >>> I = 0 >>> while B != '': ... I = I * 2 + (ord(B[0]) - ord('0')) ... B =
B[1:] ... >>> I 13 A left-shift operation (I << 1) would have the same effect as multiplying by 2 here. We’ll
leave this change as a suggested exercise, though, both because we haven’t studied loops in detail yet
and because the int and bin built-ins we met in Chapter 5 handle binary conversion tasks for us in
Python 2.6 and 3.0: >>> int('1101', 2) # Convert binary to integer: built-in 13 >>> bin(13) # Convert
integer to binary '0b1101' Given enough time, Python tends to automate most common tasks! Changing
Strings Remember the term “immutable sequence”? The immutable part means that you can’t change a
string in-place (e.g., by assigning to an index): >>> S = 'spam' >>> S[0] = "x" Raises an error! So, how do
you modify text information in Python? To change a string, you need to build and assign a new string
using tools such as concatenation and slicing, and then, if desired, assign the result back to the string’s
original name: >>> S = S + 'SPAM!' # To change a string, make a new one >>> S 'spamSPAM!' >>> S = S[:4]
+ 'Burger' + S[−1] >>> S 'spamBurger!' The first example adds a substring at the end of S, by
concatenation (really, it makes a new string and assigns it back to S, but you can think of this as
“changing” the original string). The second example replaces four characters with six by slicing, indexing,
and concatenating. As you’ll see in the next section, you can achieve similar effects with string method
calls like replace:

You might also like