[C011] Python-Basic tutorial (2)

Source: Internet
Author: User

Chapter 3: Using strings

Basic string operations

 

>>> format = "Hello,%s,%s enough for ya?">>> values = ('world','Hot')>>> print format % valuesHello,world,Hot enough for ya?
>>> format = "Pi with three decimals: %.3f">>> from math import pi>>> print format % piPi with three decimals: 3.142

Simple Conversion

 

 

>>> 'Price of eggs: $%d' % 42'Price of eggs: $42'>>> 'Hexadecimal price of eggs: %x' % 42'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'Using str: 42'>>> 'Using repr: %r' % 42L'Using repr: 42L'


Field width and precision

 

 

>>> '% 10f' % pi '000000' >>>' % 10.2f' % pi '000000' >>>' %. 5s '%' Guido van Rossum ''Guido '>>>' %. * s '% (5, 'guido van rosblum') # You can use an expression to customize the number 'guid'

Symbol, alignment, and 0 Filling

 

 

>>> '%010.2f' % pi'0000003.14'>>> 0108>>> '%-10.2f' % pi'3.14      '
>>> print('%5d' % 10) + '\n' + ('%5d' % -10)   10  -10
>>> print('%+5d' % 10) + '\n' + ('%+5d' % -10)  +10  -10

3-1

 

 

# Print a formatted price list with a given widthwidth = input('Please enter width: ')price_width = 10item_width = width - price_widthheader_format = '%-*s%*s'format       = '%-*s%*.2f'print '=' * widthprint header_format % (item_width, 'Item', price_width, 'Price')print '-' * widthprint format % (item_width, 'Apples', price_width, 0.4)print format % (item_width, 'Pears', price_width, 0.5)print format % (item_width, 'Cantaloupes', price_width, 1.92)print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8)print format % (item_width, 'Prunes (4 lbs.)', price_width, 12)print '=' * width

String Method

 

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>>> title.find('Flying')15>>> title.find('Xircus')-1>>> subject = '$$$ Get rich now!! $$$'>>> subject.find('$$$')0>>> subject.find('$$$',1)19>>> subject.find('!!')16>>> subject.find('!!',0,16)-1

Join

 

 

>>> seq = ['1','2','3','4','5']>>> sep.join(seq)'1+2+3+4+5'>>> dirs = '','usr','bin','env'>>> '/'.join(dirs)'/usr/bin/env'>>> ''.join(seq)'12345'>>> print 'C:' + '\\'.join(dirs)C:\usr\bin\env

Lower

 

 

>>> name = 'Gumby'>>> names = ['gumby','smith','jones']>>> if name.lower() in names: print 'Found it!'Found it!

Replace

 

 

>>> 'This is a test'.replace('is','eez')'Theez eez a test'

Split

 

 

>>> '1+2+3+4+5'.split('+')['1', '2', '3', '4', '5']>>> '/user/bin/env'.split('/')['', 'user', 'bin', 'env']>>> 'Using the default'.split()['Using', 'the', 'default']

Strip (remove spaces or symbols on both sides)

 

 

>>> '        internal whitespace is kept        '.strip()'internal whitespace is kept'>>> names = ['gumby','smith','jones']>>> name = 'gumby'>>> if name.strip() in names: print 'Found it!'Found it!>>> '***SPAM * for * everyone!!! ***'.strip(' *!')'SPAM * for * everyone'

 

Chapter 4: dictionary: when the index is poor

Create and use dictionaries

 

>>> phonebook = {'Alice':'2341','Beth':'9102','Cecil':'3258'}>>> phonebook['Alice']'2341'

Dict Functions

 

 

>>> items = [('name','Gumby'),('age',42)]>>> d = dict(items)>>> d{'age': 42, 'name': 'Gumby'}>>> d = dict(name = 'Gumby' , age = 32)>>> d{'age' : 32, 'name' : 'Gumby'}

Basic dictionary operations

 

 

>>> x = {}>>> x[42] = 'Foobar'>>> x{42: 'Foobar'}

4-1 dictionary example

 

# A simple database# A dictionary with person names as keys. Each person is represented as# another dictionary with the keys 'phone' and 'addr' referring to their phone# number and address, respectively.people = {    'Alice': {        'phone': '2341',        'addr': 'Foo drive 23'    },    'Beth': {        'phone': '9102',        'addr': 'Bar street 42'    },    'Cecil': {        'phone': '3158',        'addr': 'Baz avenue 90'    }}# Descriptive labels for the phone number and address. These will be used# when printing the output.labels = {    'phone': 'phone number',    'addr': 'address'}name = raw_input('Name: ')# Are we looking for a phone number or an address?request = raw_input('Phone number (p) or address (a)? ')# Use the correct key:if request == 'p': key = 'phone'if request == 'a': key = 'addr'# Only try to print information if the name is a valid key in# our dictionary:if name in people: print "%s's %s is %s." % \    (name, labels[key], people[name][key])

>>> phonebook = {'Beth':'9102','Alice':'2341','Cecil':'3258'}>>> phonebook{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}>>> phonebook['Alice']'2341'>>> "Cecil's phone number is %(Cecil)s." % phonebook"Cecil's phone number is 3258."

Dictionary Method

Clear

 

>>> d = {}>>> d['name'] = 'Gumby'>>> d['age'] = 42>>> d{'age': 42, 'name': 'Gumby'}>>> returned_value = d.clear()>>> d{}>>> print returned_valueNone>>> x = {}>>> y = x>>> x['key'] = 'value'>>> y{'key': 'value'}>>> x = {}>>> y{'key': 'value'}>>> x{}>>> x = {}>>> y = x>>> x['key'] = 'value'>>> y{'key': 'value'}>>> x.clear()>>> y{}>>> x = {}>>> x['key'] = 'value'>>> x{'key': 'value'}>>> x.clear()>>> x{}

Copy (light copy) (reference)

 

 

>>> x = {'username':'admin','machines':['foo','bar','baz']}>>> y = x.copy()>>> y['username'] = 'mlh'>>> y{'username': 'mlh', 'machines': ['foo', 'bar', 'baz']}>>> y['machines'].remove('bar')>>> y{'username': 'mlh', 'machines': ['foo', 'baz']}

Deepcopy (copy)

 

 

>>> from copy import deepcopy>>> d = {}>>> d['names'] = ['Alfred','Bertrand']>>> c = d.copy()>>> dc = deepcopy(d)>>> d['names'].append('Clive')>>> c{'names': ['Alfred', 'Bertrand', 'Clive']}>>> dc{'names': ['Alfred', 'Bertrand']}

Fromkeys

 

 

>>> {}.fromkeys(['name','age']){'age': None, 'name': None}>>> dict.fromkeys(['name','age'],'Unknow'){'age': 'Unknow', 'name': 'Unknow'}

Get

 

 

>>> d = {}>>> print d['name']Traceback (most recent call last):  File "<pyshell#67>", line 1, in <module>    print d['name']KeyError: 'name'>>> print d.get('name')None>>> d.get('name','N/A')'N/A'>>> d['name'] = 'Eric'>>> d.get('name')'Eric'

Has_key

 

 

>>> d = {}>>> d.has_key('name')
>>> d = {'title':'Python Web Site','url':'http://www.python.org','spam':0}>>> d.items()[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]>>> it = d.iteritems()>>> it<dictionary-itemiterator object at 0x01F526F0>>>> list(it)[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]>>> 

False>>> d['name'] = 'Eric'>>> d.has_key('name')True>>>

 


Items and iteritems
>>> d = {'title':'Python Web Site','url':'http://www.python.org','spam':0}>>> d.items()[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]>>> it = d.iteritems()>>> it<dictionary-itemiterator object at 0x01F526F0>>>> list(it)[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]>>> 

Keys and iterkeys

Pop

>>> d = {'x':1,'y':2}>>> d.pop('x')1>>> d{'y': 2}

Popitem

>>> d = {'url':'http://www.python.org','spam':0,'title':'Python Web Site'}>>> d.popitem()('url', 'http://www.python.org')>>> 

Setdefault

>>> d = {}>>> d.setdefault('name','N/A')'N/A'>>> d{'name': 'N/A'}>>> d['name'] = 'Gumby'>>> d.setdefault('name','N/A')'Gumby'>>> d{'name': 'Gumby'}>>> 

Update

>>> d = {'title':'Python Web Site','url':'http://www.python.org','changed':'Mar 14 22:09:15 MET 2008'}>>> x = {'title':'Python Language Website'}>>> d.update(x)>>> d{'url': 'http://www.python.org', 'changed': 'Mar 14 22:09:15 MET 2008', 'title': 'Python Language Website'}>>> 

Values and itervalues

>>> d = {}>>> d[1] = 1>>> d[2] = 2>>> d[3] = 3>>> d[4] = 1>>> d.values()[1, 2, 3, 1]>>> d{1: 1, 2: 2, 3: 3, 4: 1}>>> 

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.