Python--String list tuple dictionary

Source: Internet
Author: User
Tags delete key

Small Q  Spray intentionally thousand heavy snow peach no Words a team spring a pot of wine a pole lun the world like Lennon there are several people. ---Li yu "fishing songs son"

---------------------------------------------------------------------------------------

The sequence is the most basic data structure in Python. The position of each element in the sequence has its corresponding number encoding or index such as the first element of the encoding is 0 the second element of the index is 1 ...

Built-in functions such as index, slice, add, multiply, check member's additional length, maximum minimum value, can be performed in a sequence

Python has 6 sequences of built-in type lists, tuples, strings, Unicode strings, buffer objects, and Xrange objects.

string ===========================================================

The string is the most commonly used data type in Pyhton, which can be created with single or double quotes. As follows

var1 = ' Hello world ' var2 = "python runoob" print "var1[0]:", var1[0] >>>>> var1[0]: H print "va R2[1:3] ", Var2[1:3] >>>>> Var2[1:3]: Yth

String update

#!/usr/bin/python#-*-coding:utf-8-*-var1 = ' Hello world! ' Print "Update string:-", var1[:6] + ' runoob! ' >>>>> Update string:-Hello runoob!

Python Escape CharacterUse a backslash to escape when special characters are required.
\ (at end of line) continuation character
\ \ backslash Symbol
\ ' Single quotation mark
\ "Double quotation marks
\a Bells
\b Backspace (Backspace)
\e Escape
\000 Empty
\ nthe line break
\v Portrait tab
\ t Transverse tab
\ r Enter
\f Page Change
\oyy octal number yy represents characters such as \o12 for line breaks
\XYY hexadecimal number yy represents a character such as \x0a for line break
\other other characters are output in normal format
Python string operator+, *, [], [:], in, not in, r/r,% examples

#!/usr/bin/python# -*- coding: utf-8 -*-a =   "Hello" b =  "Python" print  "a + b  output",  a + b print   "a * 2  output result", a * 2 print  "a[1]  output",  a[1] print   "a[1:4]  output",  a[1:4] if (  "H"  in a)  :    print   "h  in variable  a "  else :    print  "h  not in variable  a  " if ( " M " not in a)  :    print " m  is not in variable  a   " else :    print " m  in variable  a  "Print r ' \ n ' Print  r ' \ n ' >>>>>a + b  output results  HelloPythona * 2  output   hellohelloa[1]  output  ea[1:4]  output  ellH  in variable  a  m  not in variable  a  \ n 

Pythoh Example of string formatting %

Print "My name is%s and weight are%d kg"% ' teng ',60>>>>> my name is teng and weight is

Symbol description
%c formatted character and its ASCII code
%s formatted string
%d formatted integer
%u format unsigned integer
%o Formatting an unsigned octal number
%x format unsigned hexadecimal number
%x format unsigned hexadecimal number uppercase
%f formatting floating-point numbers to specify the precision after a decimal point
%e format floating-point numbers with scientific notation
%E function and%E using scientific notation to format floating-point numbers
Shorthand for%g%f and%e
Shorthand for%G%f and%E
%p the address of a variable with hexadecimal number format
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/80/63/wKioL1c_2xvSDahOAABdPFJalms713.png "title=" 1.png " alt= "Wkiol1c_2xvsdahoaabdpfjalms713.png"/>
Unicode String

U ' Hello world! ' >>>>> u ' Hello world! '

The lowercase "u" before the quotation mark indicates that a Unicode string is created here. If you want to add a special character you can use Python's Unicode-escape encoding. As shown in the following example

U ' Hello\u0020world! ' >>>>> u ' Hello world! '

The \u0020 at this time represents a Unicode character space that encodes a value of 0x0020.
List ===========================================================
Format var=[' Teng ', ' C ', 1997, 20002]
For example

#!/usr/bin/pythonlist = [1, 2, 3, 5, 6, ' A ', ' abc '];p rint list[0]print "list[-2]" List[-2]print "List[1:4]:", list[1:4]p Rint "list[1:]", list[1:]print "list[-5:-1]:", list[-5:-1]>>>>>>1list[-2]: Alist[1:4]: [2,3,4]list [1:]: [2, 3, 5, 6, A, ' abc ']list[-5:-1]:[3, 5, 6, ' a ']

Update Delete list element

#!/usr/bin/pythonlist = [' physics ',  ' chemistry ',  1997, 2000];p rint  "value available at index 2 : " print list[2]; LIST[2] = 2001;PRINT LIST[2];d el list[2];p rint  "after deleting value  at index 2 :  " list>>>>>>value available at index  2 : 19972001after deleting value at index 2 :[' Physics ',  ' Chemistry ',  2000] 

list operators   functions   and methods
650) this.width=650, "src=" Http://s5.51cto.com/wyfs02/M00/80/7F/wKiom1dDBLPwxFyvAAAn2bmhRd8915.png "title=" 1.png "alt= "Wkiom1ddblpwxfyvaaan2bmhrd8915.png"/>
650) this.width=650; src= http://s5.51cto.com/wyfs02/M01/80/7F/ Wkiom1ddbmccuqvlaaa1cgto2ko008.png "title=" 2.png "alt=" Wkiom1ddbmccuqvlaaa1cgto2ko008.png "/>

method
1 list.append (obj)
Adds a new object at the end of the list
2 list.count (obj)
Statistics an element in Number of occurrences in the list
3 list.extend (seq)
Append multiple values from another sequence at the end of the list expand the original list with a new list
4 list.index (obj)
Find a value from the list the index position of the first occurrence
5 list.insert (Index, O BJ)
Insert object into List
6 list.pop (obj=list[-1])
Remove an element from the list default last element and return the value of the element
7 list.remove (obj)
Remove the first occurrence of a value in a list
8 list.reverse () Reverse list elements
9 list.sort ([func])
Sort the original list

tuple ===========================================================
A python tuple is similar to a list in that its elements cannot be modified and use parentheses.
For example

#!/usr/bin/pythontup = (1, 2, 3, 444, ' A ', ' Tom ', ' + ');p rint tup[2]print tup[-3]print "tup[1:]:", Tup[1:5]print "tup[-6 : -2]: ", Tup[-6:-2]>>>>>>3atup[1:]: (2, 3, 444, ' A ', ' Tom ', ' + ') Tup[-6:-2]: (2, 3, 444, ' a ')

Modify Delete Element
Elements in tuples are not allowed to be modified, but they can be combined to join groups of tuples

#!/usr/bin/python#-*-Coding:utf-8-*-tup1 = (n, 34.56); tup2 = (' abc ', ' X '); # The following modification of tuple element operations is illegal. # Tup1[0] = 100;# Create a new tuple Tup3 = Tup1 + tup2;print tup3;>>>>>> (34.56, ' abc ', ' X ')

Elements in a tuple are not allowed to be deleted, but you can use the DEL statement to delete an entire tuple after the tuple is deleted when the re-print tuple has an error message.

#!/usr/bin/pythontup = (' Physics ', ' Chemistry ', 1997, $);p rint Tup;del tup;print "after deleting tup:" Print tup;

tuple operator built-in functions and Methods

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/80/7E/wKioL1dDEpmTZoerAAA38UTQqYc009.png "style=" float: none; "title=" 2.png "alt=" Wkiol1ddepmtzoeraaa38utqqyc009.png "/>

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/80/80/wKiom1dDEanRLrAwAAAqPv51UGU971.png "style=" float: none; "title=" 1.png "alt=" Wkiom1ddeanrlrawaaaqpv51ugu971.png "/>

The built-in methods for tuples can be tab-Ipython in the

Tup.count (Element)
Tup.index (Element) ..... ..... ..... ......................
Special Separators
Arbitrarily unsigned objects are separated by commas by default as a tuple of the following instances

#!/usr/bin/pythonprint  ' abc ', -4.24e93, 18+6.6j,  ' XYZ ';x, y = 1, 2;print  "value of x , y : ", x,y; >>>>>>abc -4.24e+93  (18+6.6j)  xyzvalue of x , y :  1 2 (' Physics ',  ' chemistry ',  1997, 2000) after deleting tup :traceback   (most recent call last):  file  "test.py", line 9, in  <module>    print tup; nameerror: name  ' Tup '  is not defined 

dictionary ==================================================== =======
dictionary is another mutable container model and can store any type of object.
Each key-value pair is used (:) split each pair with (,) to split the entire dictionary included in curly braces ({})
           key must be unique value not unique
         The    value may be of any data type but the key must be fixed.

Format d = {key1:value1, key2:value2}
Lift & nbsp;  example  

#!/usr/bin/python dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '}; Print dict[' Name '];p rint "dict[' age '):", dict[' age ');p rint "dict[' Alice ']:" dict[' Alice '];>>>>>>  >zaradict[' age ': 7dict[' Zara ']:traceback (most recent call last): File "test.py", line 4, in <module> print "Dict[' Alice ']:", dict[' Alice '); Keyerror: ' Alice '

Modify the Delete dictionary element

dict = {' Name ':  ' Zara ',  ' age ': 7,  ' Class ':  ' first '}; dict[' age ']  = 8;   # update existing entrydict[' School '] =  "DPS School";  # add new entry print  dict print  dict[' age '];p rint  " dict[' School ']:  ',  dict[' School '];d el dict[' name ']; #  Delete key is ' name ' entry dict.clear ();      #  Empty dictionary all entries del dict ;         #  Delete dictionary print dict[' age '];>>>>>>>>{' School ':  ' Dps school ',   ' age ': 8,  ' Name ':  ' Zara ',  ' Class ':  ' first '}8dict[' School ']:  dps  school Delete the dictionary and then output will error because the dictionary no longer exists dict[' age ']:traceback  (most recent call last):   file  "test.py", line 8, in <module>    print  "dict[" Age ']:  ',  dict[' age ']; typeerror:  ' type '  object is unsubscriptable

dictionary built-in functions and methods  
650) this.width=650; " Src= "Http://s5.51cto.com/wyfs02/M02/80/7E/wKioL1dDEbmC4lfDAAA2uXAVPrM573.png" title= "1.png" alt= " Wkiol1ddebmc4lfdaaa2uxavprm573.png "/>

tr>
function and description
1 RADIANSD Ict.clear ()
Delete all elements in the dictionary
2 radiansdict.copy ()
Returns a shallow copy of a dictionary
3 Radiansdict.fromkeys ()
Creates a new dictionary with elements in the sequence SEQ Dictionary key Val is the initial value corresponding to the dictionary for all keys
4 radiansdict . Get (Key, Default=none)
Returns the value of the specified key if the value does not return the default value in the dictionary
5 radiansdict.has_key (key)
if the key Returns true in Dictionary Dict otherwise returns false
6 radiansdict.items ()
Returns a traversed (key, value) tuple array in a list
7 radiansdict.keys ()
Returns a dictionary of all keys in a list
8 radiansdict.setdefault (Key, Default=none)
and get () are similar, but if the key does not exist in the dictionary, the key is added and the value is set to default
9 radiansdict.update (dict2)
Update the key/value pairs of the dictionary dict2 to dict
ten radiansdic T.values ()
Returns all values in the dictionary as a list


Python--String list tuple dictionary

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.