Python basic teaches the 3rd chapter using strings

Source: Internet
Author: User

Tag:site   trim    string manipulation    expec   parent    height   edit   sla   font   

Python 2.7.5 (default, May, 22:43:36) [MSC v.1500 + bit (Intel)] on Win32type "copyright", "credits" or "license ( ) "For more information. #3.1 Basic string operation >>> website = ' http://www.python.org ' >>> website[-3:]= ' COM ' Traceback (most recent): File "<pyshell#1>", line 1, in <module> website[-3:]= ' com ' TypeError : ' Str ' object does not support item assignment#3.2 string formatting: Lite >>> format = "Hello,%s.%s is enough for ya?" >>> values = ("World", "hot") >>> print format% Valueshello, world. Hot was enough for ya?>>> format = ' Pi with three decimals:%.3f ' >>> from math import pi>>> prin T format% pipi with three decimals:3.142# template strings >>> from string import template>>> s = Template (' $x, Glo rious $x! ') >>> S.substitute (x= ' Slurm ') ' Slurm, glorious slurm! ' >>> s = Template ("It ' s ${x}tastic!") >>> S.substitute (x= ' Slurm ') "It ' s slurmtastic!" >>> s = Template ("MakE $$ selling $x! ") >>> S.substitute (x= ' Slurm ') ' Make $ selling slurm! ' >>> s = Template (' A $thing must never $action. ') >>> d={}>>> d[' thing ']= ' gentleman ' >>> d[' action ']= ' show his socks ' >>> S.substitute (d) ' A gentleman must never show his socks. ' >>> Error #saft_substitute不会因缺少值或不对使用 $ character .>>> '%s plus%s Equlas%s '% (1,1,2) ' 1 plus 1 Equlas 2 ' >>&gt ;    '%s plus%s equlas%s '% 1,1,2traceback (most recent call last): File "<pyshell#24>", line 1, in <module>  '%s plus%s equlas%s '% 1,1,2typeerror:not enough arguments for format string>>> '%s plus%s equlas%s '% 1,1,2 # lacks parentheses!  Traceback (most recent): File "<pyshell#25>", line 1, in <module> '%s plus%s equlas%s '% 1,1,2 # lacks parentheses! Typeerror:not enough arguments for format string#3.3 string formatting: Full version of #3.3.1 simple conversion >>> ' price of eggs: $%d '% "price of Eggs: $42 ' >>> ' hexadecimal price of eggs:%x '% hexadecimal price of eggs:2a ' >>> from math import pi>>> ' pi:%f ... '% pi ' pi:3.141593 ... ' >>> ' Very inexact estimate of pi:%i '% pi ' Very inexact estimate of Pi:3 ' >>> ' Using str:%s '% 42L ' usin G str:42 ' >>> ' using repr:%r '% 42L ' using repr:42l ' #3.3.2 Field width and precision >>> '%10f '% pi ' 3.141593 ' >>&gt ; '%10.2f '% pi ' 3.14 ' >>> '%.2f '% pi ' 3.14 ' >>> '%.5s '% ' Guido van Rossum ' Guido ' >>> '%.*s ' % (5, ' Guido van Rossum ') ' Guido ' #3.3.3 symbols, aligned and 0 fills >>> '%010.2f '% pi ' 0000003.14 ' >>> 0108>>> '%- 10.2f '% pi ' 3.14 ' >>> print ('% 5d '%) + ' \ n ' + ('% 5d '% -10) fsyntaxerror:invalid syntax>>> PR Int ('% 5d ') + ' \ n ' + ('% 5d '% -10) 10-10>>> print ('% 5d '%) + ' \ n ' + ('% 5d '% -10) fsyntaxerror:i Nvalid syntax>>> print ('% 5d ') + ' \ n ' + ('% 5d '% -10) 10-10>>> print ('%+5d '%) + ' \ n ' + ( '%+5d '% -10) +10-10 #代码清Single 3-1 string format Demo sample #3.4 string method The #string module also contains constants and functions that cannot be used as strings >>> import string>>> string.digits ' 0123456789 ' >>> string.letters ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ' >>> String.lowercase ' abcdefghijklmnopqrstuvwxyz ' >>> string.uppercase ' abcdefghijklmnopqrstuvwxyz ' >> > string.punctuation '! #$%&\ ' () *+,-./:;<=>?

@[\\]^_`{|} ~ ' >>> string.printable ' 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz! ' #$%&\ ' () *+,-./:;<=>[email protected][\\]^_ ' {|} ~ \t\n\r\x0b\x0c ' >>> string.ascii_letters ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ' #3.4.1 Find>>> ' with a moo-moo here. and a Moo-moo there '. Find (' Moo ') 7>>> title = "Monty Python ' s Flying Circus" >>> title.find (' Monty ') 0 >>> title.find (' Python ') 6>>> titie.find (' Flying ') Traceback (most recent call last): File "< Pyshell#59> ", line 1, in <module> titie.find (' Flying ') nameerror:name ' titie ' are not defined>>> title . Find (' Flying ') 15>>> title.find (' Zirquss ') -1>>> subject = ' $$$ Get rich now!!! $$$ ' >>> subject.find (' $$$ ') 0>>> subject.find (' $$$ ', 1) 20>>> subject.find ('!!! ') 16>>> subject.find ('!!! ', 0, +) -1#3.4.2 join>>> seq = [1,2,3,4,5]>>> Sep = ' + ' >>> se P.join(seq) Traceback (most recent): File ' <pyshell#69> ', line 1, in <module> sep.join (seq) Typeerror:sequen CE item 0:expected string, int found>>> seq = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']>>> sep.join (seq) ' 1+2+3+4+5 ' >& Gt;> dirs = ', ' usr ', ' bin ', ' env ' >>> '/'. Join (dirs) '/usr/bin/env ' >>> print ' C: ' + ' \ \ '. Join (dirs) c : \usr\bin\env#3.4.3 lower>>> ' Trondheim Hammer Dance '. Lower () ' Trondheim Hammer Dance ' >>> if ' Gumby ' In [' Gumby ', ' Smith ', ' Jones ']: print ' Found it! ' >>> name= ' Gumby ' >>> names=[' Gumby ', ' Smith ', ' Jones ']>>> if Name.lower () in Names:print ' Found it! ' Found it! #标题转换 >>> "That's All Folks". Title () "That's all Folks" >>> import string>>> String.capwords ("That's all, folks") "That's all, folks" #3.4.4 replace>>> ' This is a test '. Replace (' is ', ' EEZ ') ' Theez EEZ a test ' #3.4.5 split>>> ' 1+2+3+4+5 '. Split (' + ') [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']>>> '/usr/bin/env '.Split ('/') [', ' usr ', ' bin ', ' env ']>>> ' using the default '. Split () [' Using ', ' the ', ' Default '] #3.4.6 Strip Equivalent to String.Trim () >>> ' internal whitespace is kept ' in Java. strip () ' internal whitespace is kept ' &GT;&GT;&G T names = [' Gumby ', ' Smith ', ' Jones ']>>> name = ' Gumby ' >>> if name in Names:print ' Found it! ' Found it!>>> ' * * * * SPAM * for * everyone!!! '. Strip (' *! ') ' SPAM * for * everyone ' #3.4.7 translate>>> from string import maketrans>>> table = Maketrans (' cs ', ' KZ ') & gt;>> len (table) 256>>> table[97:123] ' abkdefghijklmnopqrztuvwxyz ' >>> maketrans (', ') [ 97:123] ' abcdefghijklmnopqrstuvwxyz ' >>> table = Maketrans (' cs ', ' KZ ') >>> ' This was an incredible test '. Translate (table) ' Thiz iz an inkredible tezt ' >>> ' This is an incredible test '. Translate (table, ') ' Thizizaninkredibletezt ' #非英语字符串问题table = Maketrans (' x ', ' x ') word = ' Xxx ' Print word.translate (table). lower () print U ' Xxx '. Lower () #Summary # This chapter describes two important ways to use a string: # string formatting-the modulo operator (%) can be used to convert other values to a string that contains a conversion flag, such as%s. It can also be used to format values in different ways, #包含左右对齐, set field width and precision, add symbols (plus sign ) or the left padding number 0, and so on. #字符串方法 some are useful, for example, split and join, some are used very little, for example Istitle or capitalize. #本章的新函数 #string.capwords (s[, Sep]) Use the Split function to cut the string s (with Sep as a delimiter), use the Capitalize function to capitalize the first letter of each word that is cut, and concatenate the words with the Join function using Sep as a delimiter # #string.maketrans (from,to) Create a conversion table for conversion # What's next? Lists, strings and dictionaries are the 3 most important data types in Python.

Code Listing 3-1 Example of string formatting demo

#e3 -1# uses the given width to print the formatted price list width = input (' plese enter width: ') price_width = 10item_width = Width-price_width; #减号 (-1) to align Left Numeric Header_format = '%-*s%*s ' format = '%-*s%*.2f ' print ' = ' * widthprint header_format% (item_width, ' item ', Price_width, ' P Rice ') print '-' * widthprint format% (item_width, ' Apples ', Price_width, 0.4) print format% (item_width, ' Pears ', price_w Idth, 0.5) print format% (item_width, ' cantaloupes ', price_width, 1.92) print format% (item_width, ' dried apricots (+ oz. ) ', Price_width, 8) print format% (Item_width, ' prunes (4 lbs.) ', Price_width, ') print ' = ' * Width#python E3-1.py#plese E Nter width:35#=================================== #Item price#----------------------------------- #Apples 0.40#pears 0.50#cantaloupes 1.92#dried Apricot        S (Oz.)               8.00#prunes (4 lbs.) 12.00#===================================


Python basic teaches the 3rd chapter using strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.