Basic Python Tutorial (v)

Source: Internet
Author: User

String Basic operation

All standard sequence operations (indexes, shards, multiplication, judging membership, seeking length, taking minimum and maximum values) also apply to strings, which are already described in the previous steps. However, be aware that the strings are immutable.

Method of String:

Strings "Inherit" a lot of methods from the string module, here are just a few things that are particularly useful.

1.Find

The Find method can find substrings in a longer string. It returns the leftmost index of the location where the substring is located. Returns -1 if it is not found .

' Witha moo-moo here and a Moo-moo ther'. Find ('moo'"Monty Pyhon ' s Flying circus" >& Gt;> title.find ('Monty') 0>>> title.find ('Python')-1 

2. Join

The join method is a very important string method, which is the inverse method of the split method, which is used to add elements to the queue:

>>> seq = [‘1‘,‘2‘,‘3‘,‘4‘,‘5‘]>>> Sep =‘+' >>>Sep.join (seq)‘1+2+3+4+5' >>> dirs =‘‘, "usr",  ' bin",  env ">>> " /" .join (dirs)  "/usr/bin/env" >> > print  "c: "+  ' \\" Span style= "COLOR: #000000" >.join (dirs) C:\usr\bin\env         

3, lower

The lower method returns the lowercase master of the string.

This approach comes in handy if you want to write "case-insensitive" code ----- code ignores the case state.

'Trondheim Hammer Dance'. Lower ()'Trondheim Hammer Dance'     

4. Replace

The Replace method returns a string after all occurrences of a string have been replaced.

' This wasa test'. Replace ('is ','eez')'theez eez a test' 

If you have used the "Find and replace" feature in the word processing tool, you will not be questioning the usefulness of this method.

5. Split

This is a very important method, which is the inverse method of join, used to split the string into a sequence.

>>>‘1+2+3+4+5'. Split (‘+‘)[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘]>>>‘/usr/bin/env'. Split (‘/‘) [ ",  ' usr",  ' bin< Span style= "COLOR: #800000" > ",  ' env ]>>> "  Using the Default ' .split () [  "using",  ' the", default "       

6, Strip

The Strip method returns a string that strips both sides (without inner) spaces:

'      internal white space was kept    '. Strip ()'internal white space is kept'  

Dictionary

Use of dictionaries

The fields in the real world and the fields in Python are built so that a particular word (key) can be easily traced to find its meaning (value).

In some cases, dictionaries are more appropriate than lists:

# characterize the game board state, each key is a tuple composed of coordinate values;

# Store the number of file changes, using the filename as the key;

# Digital Phone / Address Book

Create a list of people and four-bit extension numbers:

>>> names = [‘Zhangsan‘,‘Lisi‘,‘Wangwu‘,‘Sunliu "]>>> numbers = [ '  3158 ",  ' 4326 ' ]# Query >>> numbers[names.index (zhangsan< by the following method Span style= "COLOR: #800000" > ' )]2313 "        

Creating and using dictionaries

Dictionaries can be created in the following ways

>>> phonebook = {'zhangsai':'2313','Lisi':'9102',  'Wangwu ':'3158'}            

The dictionary consists of multiple keys and their corresponding values, in the above example, the name is the key and the phone number is the value.

Dict function

You can use the dict function to build a dictionary from a sequence of other mappings (such as other dictionaries) or (keys, values).

>>> items = [(‘Name‘,‘Gumby ' age", 42)]>>> D = Dict (items) > >> D{ "age name":  "gumby" }>>> d[ "name ' ] " Gumby "           

The Dict function can also create a dictionary from a keyword argument, as shown in the following example:

>>> d = dict (name ='gumby', age=42) >>> d{'age'name'  Gumby'}           

Dictionary Example:

#Simple database#Using the name of the dictionary as a key, each person in another dictionary, the key ' phone ' and ' addr ' respectively, their phone number and address,People ={‘Zhangsan‘:{‘Phone‘:‘2341‘,‘Addr‘:‘Foo Drive 23‘},‘Lisi‘:{‘Phone‘:‘9102‘,‘Addr‘:‘Bar Street 42‘},‘Wangwu‘:{‘Phone‘:‘3158‘,‘Addr‘:‘Baz Avenue 90‘} }#Descriptive labels for phone numbers and addresses are used when printing outputLabels ={‘Phone‘:‘Phone number‘,‘Addr‘:‘Address‘}name = Raw_input (‘Name:‘)#Looking for a phone number or address? Use the correct key: request = Raw_input (‘Phone number (p) or address (a)?‘)#Use the correct key:If request = =‘P': Key =‘Phone‘If request = =‘A': Key = "addr ' # If the name is a valid key in the dictionary to print information: if name in people: print " %s '%s is%s. "% (name, Labels[key], People[name][key]) 
------------------------
# input content >>> Name:zhangsanphone number (p) Or address (a)? P# Print result Zhangsan "s phone number is 2341.

Basic Python Tutorial (v)

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.