• No results found

There are a number of operations onstrobjects, operations which createstrs and operations which create other objects fromstrs.

There are three operations (‘+’ , ‘*’ , ‘[ ]’) that work with all sequences (including strs) and a unique operation, ‘%’, that can be performed only withstrobjects.

The ‘+’ operator creates a newstringas the concatenation of the arguments.

>>> "hi " + 'mom' 'hi mom'

The ‘*’ operator betweenstrand numbers (number ‘*’stror str‘*’ number) creates a new strthat is a number of repetitions of the inputstr.

>>> print 3*"cool!" cool!cool!cool!

The ‘[ ]’ operator can extract a single character or a slice from the string. There are two forms: the single-item form and the slice form.

• The single item format isstring[index]. Characters are numbered from 0 to ‘len(string)’. Characters are also numbered in reverse from -‘len(string)’ to -1.

• The slice format is string [start : end ]. Characters fromstart to end -1 are chosen to create a new stras a slice of the originalstr; there will beend−startcharacters in the resultingstr.

Ifstart is omitted it is the beginning of thestring (position 0). Ifend is omitted it is the end of thestring(position -1).

Yes, you can omit both (‘someString[:]’) to make a copy of a string.

>>> s="adenosine" >>> s[2] 'e' >>> s[:5] 'adeno' >>> s[5:] 'sine' >>> s[-5:] 'osine' >>> s[:-5] 'aden'

The String Formatting Operation,%. The %operator is sometimes called string interpolation, since it interpolates literal text and converted values. We prefer to call it string formatting, since that is a more apt description. Much of the formatting is taken straight from the C library’sprintf()function.

This operator has three forms. You can use% with astrand value, strand a tupleas well as strand classname:dict. We’ll covertupleanddictin detail later.

The string on the left-hand side of % contains a mixture of literal text plus conversion specifications. A conversion specification begins with ‘%’. For example, integers are converted with ‘%i’. Each conversion specification will use a corresponding value from thetuple. The first conversion uses the first value of the

tuple, the second conversion uses the second value from thetuple.

For example: import random

d1, d2 = random.randrange(1,6), random.randrange(1,6) r= "die 1 shows %i, and die 2 shows %i" % ( d1, d2 )

The first ‘%i’ will convert the value ford1to astringand insert the value, the second ‘%i’ will convert the value ford2to astring. The%operator returns the newstringbased on the format, with each conversion specification replaced with the appropriate values.

Conversion Specifications. Each conversion specification has from one to four elements, following this pattern: ‘%’‘.’

[ flags ][ width [ precision ]] code

The ‘%’ and the finalcodein each conversion specification are required. The other elements are optional. The optionalflagselement can have any combination of the following values:

‘-’ Left adjust the converted value in a field that has a length given by the widthelement. The default is right adjustment.

‘+’ Show positive signs (sign will be ‘+’ or ‘-’). The default is to show negative signs only.

␣(aspace) Show positive signs with a space (sign will be ␣or ‘-’). The default is negative signs only. ‘#’ Use the Python literal rules (0 for octal, 0x for hexadecimal, etc.) The default is decoration-free notation. ‘0’ Zero-fill the the field that has a length given by thewidth element. The default is to space-fill the field.

This doesn’t make a lot of sense with the - (left-adjust) flag.

The optionalwidthelement is a number that specifies the total number of characters for the field, including signs and decimal points. If omitted, the width is just big enough to hold the output number. If a ‘*’ is used instead of a number, an item from thetupleof values is used as the width of the field. For example, ‘"%*i" % ( 3, d1 )’ uses the value 3 from thetupleas the field width andd1as the value to convert to astring. The optional precision element (which must be preceded by a dot, ‘.’ if it is present) has a few different purposes. For numeric conversions, this is the number of digits to the right of the decimal point. Forstring conversions, this is the maximum number of characters to be printed, longerstrings will be truncated. If a ‘*’ is used instead of a number, an item from thetupleof values is used as the precision of the conversion. For example, ‘"%*.*f" % ( 6, 2, avg )’ uses the value 6 from thetuple as the field width, the value 2 from thetupleas the precision andavgas the value.

The standard conversion rules also permit a long or short indicator: ‘l’ or ‘h’. These are tolerated by Python so that these formats will be compatible with C, but they have no effect. They reflect internal representation considerations for C programming, not external formatting of the data.

The required one-lettercodeelement specifies the conversion to perform. The codes are listed below. ‘%’ Not a conversion, this creates a ‘%’ in the resultingstr. Use ‘%%’ to put a ‘%’ in the outputstr. ‘c’ Convert a single-character str. This will also convert an integer value to the corresponding ASCII

character. For example, ‘"%c" % ( 65, )’ results in ‘"A"’.

‘s’ Convert astr. This will convert non-strobjects by implicitly calling the str()function. ‘r’ Call therepr()function, and insert that value.

‘i’ ‘d’ Convert a numeric value, showing ordinary decimal output. The code i stands for integer, d stands for decimal. They mean the same thing; but it’s hard to reach a consensus on which is “correct”. ‘u’ Convert anunsignednumber. While relevant to C programming, this is the same as the ‘i’ or ‘d’ format

conversion.

‘o’ Convert a numeric value, showing the octal representation. ‘%#0’ gets the Python-style value with a leading zero. This is similar to theoct() function.

‘x’ ‘X’ Convert a numeric value, showing the hexadecimal representation. ‘%#X’ gets the Python-style value with a leading ‘0X’; ‘%#x’ gets the Python-style value with a leading ‘0x’. This is similar to thehex() function.

‘e’ ‘E’ Convert a numeric value, showing scientific notation. ‘%e’ produces ±d.ddd ‘e’ ±xx, ‘%E’ produces

±d.ddd ‘E’±xx.

‘f’ ‘F’ Convert a numeric value, using ordinary decimal notation. In case the number is gigantic, this will switch to ‘%g’ or ‘%G’ notation.

‘g’ ‘G’ “Generic” floating-point conversion. For values with an exponent larger than -4, and smaller than the precision element, the ‘%f’ format will be used. For values with an exponent smaller than -4, or values larger than theprecision element, the ‘%e’ or ‘%E’ format will be used.

Here are some examples.

"%i: %i win, %i loss, %6.3f" % (count,win,loss,float(win)/loss)

This example does four conversions: three simple integer and one floating point that provides a width of 6 and 3 digits of precision. -0.000is the expected format. The rest of thestringis literally included in the output.

"Spin %3i: %2i, %s" % (spin,number,color)

This example does three conversions: one number is converted into a field with a width of 3, another converted with a width of 2, and astringis converted, using as much space as thestringrequires.

>>> a=6.02E23 >>> "%e" % a '6.020000e+23' >>> "%E" % a '6.020000E+23' >>>

This example shows simple conversion of a floating-point number to the default scientific notation which has a witdth of 12 and a precision of 6.