10 minutes Learn the basic types of Python

Source: Internet
Author: User
Tags delete key printable characters shallow copy string format string methods

One: Cause

(1) Speaking of the reasons for learning Python, the previous blog has been mentioned; Python pinch refers to the fourth large language (from contact to now 2 weeks) C/S, Java,matlab (PS: Should not be considered to be a beginner, only simple application), And then it's python.

(2) C + + to Java transition is very short, but the transition to Matla is very not smooth (PS: That is, the previous blog mentioned, from the heart of the conflict of a never met language), At that time, it was felt that the resistance to opening a new language was very large (sometimes it could be used to describe it).

(3) From Java to Python, about two or three years without learning a new language, has been consolidating the data structure and algorithm of the basic things, and C + + STL, and javaweb programming, and so on, in short, no contact with the new language, it is conceivable to accept new things resistance is how big (PS: How outdated his thoughts are); Of course, it is because of the sudden contact with a new language for a long time, for how to quickly master a language, oneself also have a little touch.

(4) Transformation of ideas and ideas--sharing of feelings

Willing to be good at accepting new things, the desire to be full of fresh knowledge;

More friends, you may be a technology a language of Daniel, you can not be proficient in door, learn from each other;

See Technical Exchange Group and technology blog and community, then delve into the official API

A strategy for opening a new technology: 1) Start with a point of interest (cultivate interest), run some small samples, 2) 1-2 days simple to pass the basic language (can be unchanged code); 3) 1-2 days start to take the tutorial inside of some small program, you manually knock over ; 4) 2-3 days apply the data type of this language and the type of packaging (similar to STL), debug it, 5) advanced advance and Advanced application, 6) summarize, summarize through always.

Second: detailed

(1) List (Lists)

1) The sequence is the most basic data structure in Python. Each element in the sequence is assigned a number-its position, or index, the first index is 0, the second index is 1, and so on.

2) Python has a built-in type of 6 sequences, but the most common are lists and tuples. sequences can be performed by operations including indexing, slicing, adding, multiplying, and checking members . In addition, Python has built-in methods for determining the length of a sequence and determining the maximum and minimum elements. A list is the most commonly used Python data type and can appear as a comma-separated value within a square bracket. A list's data items do not need to have the same type to create a list, as long as the different data items separated by commas are enclosed in square brackets. As shown below:

List1 = [' Physics ', ' Chemistry ', 1997, 2000];list2 = [1, 2, 3, 4, 5];list3 = ["A", "B", "C", "D"]; #与字符串的索引一样, the list index starts at 0. Lists can be intercepted, combined, and so on.

3) List

To use the subscript index to access the values in the list, you can also use square brackets to intercept the characters as follows: List[1:5], intercept; list[[:-1];
2--You can modify or update data items in a list, you can also use the Append () method to add list items as follows:
3--can use the DEL statement to delete the elements of the list, as in the following example: Del list[8:-1];
The 4--list pairs + and * operators are similar to strings. The + sign is used for the combined list, and the * number is used for repeating lists.

5--CMP (List1, List2) compares two elements of a list; The number of Len (list) elements; Max returns the maximum value of the list element;  MIN (list) returns the minimum value of the list element; List (seq) converts tuples to lists
6--function
List.append (obj) adds a new object at the end of the list
2 list.count (obj) counts the number of occurrences of an element in a list
3 List.extend (SEQ) appends multiple values from another sequence at the end of the list (the original list is expanded with a new list)
4 list.index (obj) find the index position of the first occurrence of a value from the list
5 list.insert (index, obj) inserts an object into the list
6 List.pop (obj=list[-1]) removes an element from the list (the last element by default) and returns the value of the element

7 List.remove (obj) removes the first occurrence of a value in a list
8 list.reverse () reverse list of elements
9 List.sort ([func]) to sort the original list

(2) Tuple method is basically the same as list

A python tuple is similar to a list, except that the elements of a tuple cannot be modified. tuples use parentheses, and the list uses square brackets.

Tuple creation is simple, just add elements in parentheses and separate them with commas. The following example:

Tup1 = (' Physics ', ' Chemistry ', 1997, n); tup2 = (1, 2, 3, 4, 5); tup3 = "A", "B", "C", "D";

(3) String strings

The string is the most commonly used data type in Python. We can use quotation marks to create strings. Creating a string is simple, as long as you assign a value to the variable

1) Python escape character when you need to use special characters in characters, Python uses a backslash (\) to escape characters. As the following table:

\ (at end of line ) continuation character
\ \ Backslash Symbol
\ ' single quotation mark
\ " double quotation marks
\ nthe line break

2) Python string operator

+ string Connection A + b output result: Hellopython

* Repeat output string a*2 output Result: Hellohello

[] get the character in a string by index a[1] output result E

[ : ] intercepts part of a string a[1:4] output ell

In member operator-if the string contains the given character returns TrueH in a output 1
Not in member operator-if the string does not contain the given character returnsTrue M not in a output result 1
R/R Raw String-Raw string: all strings are used directly as literal meanings, without escaping special or non-printable characters. The original string has almost exactly the same syntax as a normal string, except that the first quotation mark of the string is preceded by the letter "R" (which can be case). print R ' \ n ' prints \ n and print R ' \ n ' prints \ n
% format string see next section

3) Three quotation marks

python three quotes allow a string to span multiple lines, and the string can contain line breaks, tabs, and other special characters. The syntax for a triple quotation mark is a pair of consecutive single or double quotes (usually paired). three quotes allow programmers to escape from the mire of quotes and special strings, keeping a small piece of string in the form of what is known as WYSIWYG.

A typical use case is that when you need a piece of HTML or SQL, a special string escape is cumbersome when you use a string combination.

errhtml = "
4) Python string built-in function

String methods are slowly added from python1.6 to 2.0-they are also added to Jython.
These methods implement most of the methods of the string module, as shown in the following table, which lists the currently supported methods for string literals, all of which contain support for Unicode, and some are even specifically for Unicode.

Method Description

String.center (width) returns the center of the original string and fills the new string with a space of length width
String.count (str, beg=0, End=len (String)) returns the number of occurrences of STR in a string, if beg or end specifies the number of occurrences of STR in the specified range
String.decode (encoding= ' UTF-8 ', errors= ' strict ') decodes a string in encoding specified encoding format, and if an error defaults to a ValueError exception, unless errors specifies the Is ' ignore ' or ' replace '

String.encode (encoding= ' UTF-8 ', errors= ' strict ') encodes a string in encoding specified encoding format, and if an error defaults to a ValueError exception, unless errors specifies ' Ignore ' or ' replace '
string.find (str, beg=0, End=len (string)) detects if STR is contained in a string, and if beg and end specify a range, the check is contained within the specified range, or 1 if the index value of the start is returned.
String.index (str, beg=0, End=len (String)) is the same as the Find () method, except that STR does not report an exception if it is not in a string.
String.isspace () returns True if the string contains only spaces, otherwise False.

String.Lower () converts all uppercase characters in a string to lowercase.
String.lstrip () truncates the left space of a string
String.partition (str) is a bit like the combination of find () and split (), which separates string strings into a 3-element tuple from the first position in STR (string_pre_str,str,string _POST_STR), if the string does not contain str then string_pre_str = = String.
String.Replace (str1, str2, Num=string.count (STR1)) replaces str1 in string with STR2, and if NUM is specified, the substitution is not more than num times.
String.rfind (str, Beg=0,end=len (string)) is similar to the Find () function, but looks up from the right.
String.rpartition (str) is similar to the partition () function, but looks up from the right.
String.rstrip () Deletes a space at the end of a string string.
String.Split (str= "", Num=string.count (str)) slices a string with the Str delimiter, and if NUM has a specified value, only the NUM
substring is delimited
.
String.strip ([obj]) executes Lstrip () and Rstrip () on string

(4) Python dictionary (Dictionary)

A dictionary is another mutable container model, and can store any type of object , such as another container model. A dictionary consists of a pair of keys and corresponding values. Dictionaries are also referred to as associative arrays or hash tables . The basic syntax is as follows:
Dict = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}

Each key and value is separated by a colon (:), each pair is separated by commas, and the whole is placed in curly braces ({}). The key must be unique, but the value does not have to be. The value can take any data type, but it must be immutable, such as a string, number, or tuple.
1) Deleting a dictionary element deletes a single element and clears the dictionary, emptying only one operation.
Show Delete a dictionary with the Del command, as in the following example:

#coding =utf-8#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' Class ': ' First ';d el dict[' name ']; # Delete key is ' Name ' entry dict.clear ();     # Empty dictionary all Entries del dict;        # Delete the dictionary print "dict[' age ']:", dict[' age '];p rint "dict[' School ']:", dict[' School '];

2) dictionary built-in functions & Methods The Python dictionary contains the following built-in functions:
Serial number Functions and descriptions
1 cmp (Dict1, dict2) compares two dictionary elements.
2 len (dict) calculates the number of dictionary elements, that is, the total number of keys.
3 str (dict) output dictionary printable string representation.
4 Type (variable) returns the type of the variable entered, and returns the dictionary type if the variable is a dictionary.


1 Radiansdict.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 the key of the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary
4radiansdict.get (key, Default=none) returns the value of the specified key if the value does not return the default value in the dictionary
5Radiansdict.has_key (key) returns False if the key returns true in the dictionary dict
6 Radiansdict.items () returns an array of traversed (key, value) tuples in a list
7 Radiansdict.keys () returns a dictionary of all keys in a list
8 Radiansdict.setdefault (Key, Default=none) is similar to get (), but if the key does not already exist in the dictionary, the key is added and the value is set to default
9 Radiansdict.update (DICT2) updates the dictionary dict2 key/value pairs to Dict

radiansdict.values () returns all values in the dictionary as a list

5) Python Date and time

Python programs can handle dates and times in many ways. Converting a date format is a common routine chore. Python has a time and calendar module that can help.
There are many functions under the popular time module included with Python to convert common date formats. such as the function Time.time () returns the current operating system time of the record starting from 12:00am, January 1, 1970 (epoch) with the Ticks Timing unit, as in the following example:

The above is also the struct_time tuple. This structure has the following properties:

Ordinal attribute value
0 tm_year 2008
1 Tm_mon 1 to 12
2 tm_mday 1 to 31
3 Tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are leap seconds)
6 Tm_wday 0 to 6 (0 is Monday)
7 tm_yday 1 to 366 (Julian calendar)
8 tm_isdst -1, 0, 1,-1 is the flag that determines whether it is daylight saving time

Time Module

The time module contains the following built-in functions, both temporal and conversion time formats:
Serial number Functions and descriptions
1 Time.altzone
Returns the number of seconds to offset the daylight saving time region in West Greenwich. If the region returns negative values in eastern Greenwich (such as Western Europe, including the UK). Available for daylight saving time enabled regions.
2 Time.asctime ([Tupletime])
Accepts a time tuple and returns a read-only string of 24 characters in the form "Tue Dec 11 18:07:14 2008" (December 11, 2008 Tuesday 18:07 14 seconds).
3 Time.clock () returns the current CPU time for the number of seconds that are calculated as floating-point numbers. It is more useful than time.time () to measure the time spent on different programs.
4 Time.ctime ([secs]) function equivalent to Asctime (localtime (secs)), parameter equivalent to Asctime ()
6 time.localtime ([secs]) receives the time suffix (the number of floating-point seconds elapsed after the 1970 era) and returns the time tuple T (t.tm_isdst 0 or 1) under local time, depending on whether the local is daylight saving time or not.
7 Time.mktime (Tupletime) accepts the time tuple and returns the time suffix (the number of floating-point seconds elapsed after the 1970 era).
8 time.sleep (secs) postpones the call thread's run, secs refers to the number of seconds.
9 Time.strftime (Fmt[,tupletime]) receives a time tuple and returns the local time as a readable string, in the format determined by FMT.

10 Time.strptime (str,fmt= '%a%b%d%h:%m:%s%Y ') resolves a time string to a time tuple based on the format of the FMT.
Time.time () returns the timestamp of the current time (the number of floating-point seconds elapsed after the 1970 era).
12 Time.tzset () Re-initializes time-related settings according to the environment variable TZ.

Calendar Module The functions of this module are calendar related, such as printing a month's character calendar.

Monday is the default first day of the week, and Sunday is the default last day. You need to call the Calendar.setfirstweekday () function to change the settings .

The module contains the following built-in functions:

Serial number Functions and descriptions
1 Calendar.calendar (year,w=2,l=1,c=6) returns the year calendar of a multi-line string format with a 3-month line with a distance of C. The daily width interval is w characters. The length of each line is 21* w+18+2* C. L is the number of rows per week.
3 Calendar.isleap (year) is a leap year that returns true, otherwise false.
4 Calendar.leapdays (y1,y2) returns the total number of leap years between y1,y2 two.
5 calendar.month (year,month,w=2,l=1) returns a multi-line string format for year month calendar, two row headings, and one week row. The daily width interval is w characters. The length of each line is 7* w+6. L is the number of rows per week.
6 Calendar.monthcalendar (Year,month) returns a single-level nested list of integers. Each sub-list is loaded with integers representing one weeks. The date of year month is set to, and the day of the month is indicated by the number of days of the day, starting from 1.
7 Calendar.monthrange (year,month) returns two integers. The first is the day of the week of the month, and the second is the date code for that month. Day from 0 (Monday) to 6 (Sunday); The month is from 1 to 12.
Calendar.setfirstweekday (Weekday) sets the weekly start date code. 0 (Monday) to 6 (Sunday).
calendar.weekday (year,month,day) returns the date code for the given date. 0 (Monday) to 6 (Sunday). The month is 1 (January) to 12 (December).

In Python, other modules for working with dates and times are: DateTime module PYTZ Module Dateutil module

(0) Catalogue

Quickly learn python and make mistakes (text processing)

Python Text processing and JAVA/C

10 minutes Learn the basic types of Python

Fast Learning Python (actual combat)

The way to Big data processing (10 minutes to learn Python)



10 minutes Learn the basic types of Python

Related Article

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.