Getting started with Python data types, strings, and operators

Source: Internet
Author: User
Tags abs current time datetime delete key lowercase natural string square root timedelta

Here, write down what's unique in Python and what's different from C.

Data type
Force type conversions
String
Escape character
Natural string
Unicode string
The string is immutable
Name of identifier variable
Indent
Operator
Operation Precedence
1. Data type

In Python, there are 4 types of data--integers (int), long integers (length), floating-point numbers (float), and complex numbers (complex).

2 is an example of an integer.
Long integers are just larger integers. A long integer is usually followed by a number of L, such as 1000000L.
3.23 and 52.3E-4 are examples of floating-point numbers. The e tag represents a power of 10. Here, 52.3E-4 means 52.3 * 10-4.
( -5+4j) and (2.3-4.6j) are examples of complex numbers.

There's a complex number here, and it's easier to compute than C, and it's usually necessary to define the plural type yourself in C.

Force type conversions

The data types in the 4 above can be converted to each other, and can be converted to string type (str) such as:

>>> a=12343434
>>> Long (a)
12343434L
>>> Str (a)
' 12343434 '
>>> Float (a)
12343434.0
Complex (a)
(12343434+0J)
2. String

You can use single and double quotes to denote the middle as a string, which makes no difference. When there are quotes or rows in a string, you can enclose them in three quotes ("' or" ").

In C + +, use single quotes to denote char and double quotation marks for string.
Escape character

In characters, to represent slashes \, you need to use \, other special symbols are also, for example, using \ ' to denote quotes (if you don't use triple quotes). The program can use \ to indicate that two lines are joined together, for example

s = ' This is a string. \
This continues the string. '
Print S
Output:

This is a string. This continues the string.
Natural string

If you want to indicate certain strings that do not require special handling such as escape characters, then you need to specify a natural string. The natural string is specified by prefixing the string with R or R. For example, R "Newlines are indicated by \ n".

Unicode string

Unicode is the standard way to write international text. If you want to use Chinese or other non-English text, you need to have an editor that supports Unicode. Similarly, Python allows you to process Unicode text-you just prefix the string with u or U. For example, U "This is a Unicode string.".

Remember to use a Unicode string when you are working on a text file, especially if you know that the file contains text written in a non-English language.

The string is immutable

This means that once you create a string, you can't change it anymore. It may seem like a bad thing, but it's not actually. To modify a character, you can actually assign it with the original name, for example:

>>> s= ' abc '
>>> S=s[:2]
>>> Print S
Ab
3. Identifiers (name of variable)

The first character of an identifier must be a letter in the alphabet (uppercase or lowercase) or an underscore (' _ ').

Other parts of the identifier name can consist of a letter (uppercase or lowercase), an underscore (' _ '), or a number (0-9).

Examples of invalid identifier names are 2things, this are spaced out and my-name.

You only need to assign a value to a variable when you use it. You do not need to declare or define a data type.

4. Indent

Whitespace is important in python. In fact, the blank at the beginning of the line is important. It is called indentation. The whitespace (spaces and tabs) at the logical beginning of the line is used to determine the indentation level of the logical row, which is used to determine the grouping of the statements.

This means that statements at the same level must have the same indentation. Each group of such statements is called a block.

Do not mix with the space and tab, if you use tab to all the tab, if you use 4 spaces or 2 spaces are always using space. A tab and 4 spaces are not the same, even if it looks the same!

5. Operator

6. Operation Priority

The following table gives Python operator precedence, from the lowest priority (loosely bound) to the highest priority (most tightly combined). This means that in an expression, Python first evaluates the operator in the table, and then computes the operator at the top of the table

Operators are usually combined left to right, that is, operators with the same precedence are evaluated in Left-to-right order. If we want to change the order of their calculations, we have to use parentheses.

Supplementary examples

1, string
1.1. How to use strings in Python
A, use single quotes (')
Enclose a string in single quotes, for example:
Str= ' This is string ';
Print str;

b, using double quotes (")
The string in double quotes is exactly the same as the string usage in single quotes, for example:
Str= "This is string";
Print str;

C, use three quotes (' ")
Using triple quotes, which represent multiple lines of string, you can use single and double quotes freely in three quotes, for example:
Str= ' ' is string
This is Pythod string
This is string ' '
Print str;

2. Boolean type
Bool=false;
print bool;
Bool=true;
print bool;

3, Integer
int=20;
print int;

4, Floating points
float=2.3;
print float;

5, Digital
Include integers, floating-point numbers.
5.1, delete the Digital object reference, for example:
A=1;
b=2;
c=3;
Del A;
del B, C;
#print A; #删除a变量后, calling a variable will cause an error.

5.2, Number type conversion


int (x [, Base]) converts x to an integer
Float (x) converts x to a floating-point number
Complex (real [, Imag]) creates a complex number
STR (x) converts an object x to a string
REPR (x) converts an object x to an expression string
Eval (str) is used to compute a valid Python expression in a string and returns an object
Tuple (s) converts the sequence s to a tuple
List (s) converts sequence s to a list
Chr (x) converts an integer to a character
UNICHR (x) converts an integer to a Unicode character
Ord (x) converts a character to its integer value
Hex (x) converts an integer to a hexadecimal string
Oct (x) converts an integer to a octal string

5.3. Mathematical function


ABS (x) returns the absolute value of the number, such as ABS (-10) return 10
Ceil (x) returns the upper integer of a number, such as Math.ceil (4.1) Returning 5
CMP (x, y) if x < y returns-1, if x = = y returns 0, if x > y returns 1
EXP (x) returns the X Power (ex) of E, as MATH.EXP (1) returns 2.718281828459045
Fabs (x) returns the absolute value of the number, as Math.fabs (-10) returns 10.0
Floor (x) returns the lower integer of the number, as Math.floor (4.9) returns 4
Log (x), such as Math.log (MATH.E) return 1.0,math.log (100,10) return 2.0
LOG10 (x) returns the logarithm of x with a base of 10, such as MATH.LOG10 (100), returning 2.0
Max (x1, x2,...) Returns the maximum value of the given parameter, which can be a sequence.
Min (x1, x2,...) Returns the minimum value of the given parameter, which can be a sequence.
MODF (x) returns the integer part of x and the decimal part, and the numeric symbol in two parts is the same as x, and the integral part is represented by a floating-point type.
Pow (x, y) x**y the value after the operation.
Round (x [, N]) returns the rounded value of the floating-point number x, such as the value of N, which represents the digits rounded to the decimal point.
SQRT (x) returns the square root of the number x, the number can be negative, and the return type is real, as MATH.SQRT (4) returns 2+0J

6, List
6.1, initialize the list, for example:
list=[' physics ', ' Chemistry ', 1997, 2000];
Nums=[1, 3, 5, 7, 8, 13, 20];

6.2, access the values in the list, for example:


"' nums[0]: 1 '"
Print "nums[0]:", Nums[0]
' Nums[2:5]: [5, 7, 8] cut from subscript 2 to element with subscript 5, but does not include element with subscript 5
Print "Nums[2:5]:", Nums[2:5]
' Nums[1: [3, 5, 7, 8, 13, 20] cut from subscript 1 to last element '
Print "Nums[1:]:", Nums[1:]
' nums[:-3]: [1, 3, 5, 7] from the beginning of the element has been cut to the penultimate element, but does not contain the last third element ' "
Print "nums[:-3]:", nums[:-3]
' nums[: [1, 3, 5, 7, 8, 13, 20] return all elements '
Print "nums[:]:", nums[:]

6.3, update the list, for example:

Nums[0]= "LJQ";
Print Nums[0];
6.4. Delete list elements

Del Nums[0];
' Nums[: [3, 5, 7, 8, 13, 20] '
Print "nums[:]:", nums[:];
6.5. List script operator
The list of + and * operators are similar to strings. The + number is used to assemble the list, and the * is used to repeat the list, for example:

Print Len ([1, 2, 3]); #3
Print [1, 2, 3] + [4, 5, 6]; #[1, 2, 3, 4, 5, 6]
print [' hi! '] * 4; #[' hi! ', ' hi! ', ' hi! ', ' hi! '
Print 3 in [1, 2, 3] #True
For x in [1, 2, 3]: print x, #1 2 3
6.6. List interception

l=[' spam ', ' spam ', ' spam! '];
Print l[2]; # ' spam! '
Print L[-2]; # ' Spam '
Print l[1:]; #[' Spam ', ' spam! ']
6.7. List function & method


List.append (obj) adds a new object at the end of the list
List.count (obj) counts the number of times an element appears in the list
List.extend (SEQ) appends multiple values from another sequence at the end of the list (expands the original list with the new list)
List.index (obj) finds the index position of the first occurrence of a value from the list, with the index starting at 0
List.insert (index, obj) inserts an object into the list
List.pop (obj=list[-1]) removes an element from the list (the default last element) and returns the value of the element
List.remove (obj) removes the first occurrence of a value in the list
List.reverse () reverse the elements in the list, inverted
List.sort ([func]) sort the original list

7. Tuple (Yuan Group)

Python's tuples are similar to lists, except that the elements of a tuple cannot be modified; tuples use parentheses (), and the list uses brackets []; The tuple creation is simple, simply by adding elements in parentheses and separating them with commas (,), for example:

Tup1 = (' Physics ', ' Chemistry ', 1997, 2000);
Tup2 = (1, 2, 3, 4, 5);
Tup3 = "A", "B", "C", "D";

Create an empty tuple, for example: Tup = ();

When there is only one element in a tuple, you need to add a comma after the element, for example: Tup1 = (50,);

Tuples are similar to strings, the subscript index starts at 0 and can be intercepted, combined, and so on.

7.1, access to the META Group

Tup1 = (' Physics ', ' Chemistry ', 1997, 2000);
#tup1 [0]: Physics
Print "tup1[0]:", tup1[0]
#tup1 [1:5]: (' Chemistry ', 1997)
Print "Tup1[1:5]:", Tup1[1:3]
7.2, modify the META Group
The element values in a tuple are not allowed to be modified, but we can make a combination of tuples, for example:
Tup1 = (12, 34.56);
tup2 = (' abc ', ' XYZ ');

# The following modification of tuple element operations is illegal.
# tup1[0] = 100;

# Create a new tuple

Tup3 = Tup1 + tup2;
Print Tup3; # (34.56, ' abc ', ' XYZ ')
7.3. Delete tuples
The element values in the tuple are not allowed to be deleted, and you can use the DEL statement to delete the entire tuple, for example:

Tup = (' Physics ', ' Chemistry ', 1997, 2000);
Print tup;
Del Tup;
7.4. Tuple operators
As with strings, the + and * numbers can be used between tuples. This means that they can be combined and copied, and a new tuple will be generated after the operation.


7.5, meta-Group Index & interception

L = (' spam ', ' spam ', ' spam! ');
Print l[2]; # ' spam! '
Print L[-2]; # ' Spam '
Print l[1:]; #[' Spam ', ' spam! ']
7.6, the tuple built-in functions

CMP (Tuple1, tuple2) compares two tuple elements.
Len (tuple) calculates the number of tuple elements.
Max (tuple) returns the maximum value of an element in a tuple.
MIN (tuple) returns the minimum value of the element in a tuple.
Tuple (SEQ) converts the list to tuples.
8. Dictionary

8.1. Introduction to the Dictionary
The Dictionary (dictionary) is the most flexible built-in data structure type in Python except the list. A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys rather than by offsets.

A dictionary consists of a key and a corresponding value. Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:

Dict = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '};
You can also create a dictionary like this:

Dict1 = {' abc ': 456};
Dict2 = {' abc ': 123, 98.6:37};
Each key and value must be 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 is not necessary; values can take any data type, but must be immutable, such as strings, numbers, or tuples.

8.2, access to the value of the dictionary

#!/usr/bin/python
Dict = {' name ': ' Zara ', ' age ': 7, ' class ': ' A ';
print "dict[' name ']:", dict[' name ';
Print "dict[' age ']:", dict[' age ';
8.3, modify the dictionary
The way to add new content to a dictionary is to add new key/value pairs, modify or delete existing key/value pairs as follows:

#!/usr/bin/python
Dict = {' name ': ' Zara ', ' age ': 7, ' class ': ' A ';
dict["Age"]=27; #修改已有键的值
dict["School"]= "Wutong"; #增加新的键/value pairs
Print "dict[' age ']:", dict[' age ';
Print "dict[' School ']:", dict[' school '];
8.4, delete the dictionary
Del dict[' name ']; # Delete key is ' name ' entry
Dict.clear (); # Empty Dictionary all entries
Del Dict; # Delete Dictionary
For example:

#!/usr/bin/python
Dict = {' name ': ' Zara ', ' age ': 7, ' class ': ' A ';
Del dict[' name '];
#dict {' Age ': 7, ' class ': ' I '}
Print "Dict", dict;
Note: The dictionary does not exist, Del will throw an exception

8.5. Dictionary built-in Functions & methods


CMP (Dict1, dict2) compares two dictionary elements.
Len (dict) calculates the number of dictionary elements, that is, the total number of keys.
The str (dict) output dictionary is a printable string representation.
Type (variable) returns the type of the variable entered and, if the variable is a dictionary, returns the dictionary type.
Radiansdict.clear () Delete all elements in the dictionary
Radiansdict.copy () returns a shallow copy of a dictionary
Radiansdict.fromkeys () Creates a new dictionary, the key of the dictionary for the elements in the sequence seq, and Val is the initial value for all keys in the dictionary.
Radiansdict.get (key, Default=none) returns the value of the specified key, if the value does not return a default value in the dictionary
Radiansdict.has_key (key) returns False if the key returns true in the dictionary Dict
Radiansdict.items () returns a traversal (key, value) tuple array as a list
Radiansdict.keys () returns a dictionary with a list of all keys
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
Radiansdict.update (DICT2) updates the dictionary dict2 key/value pairs into dict
Radiansdict.values () returns all values in the dictionary to the list

9, date and time

9.1. Get the current time, for example:
Import time, DateTime;

LocalTime = Time.localtime (Time.time ())
#Local Current Time:time.struct_time (tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, t M_YDAY=80, tm_isdst=0)
Print "Local Current time:", localtime
Description: Time.struct_time (tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_ isdst=0) belongs to the Struct_time tuple, and the Struct_time tuple has the following properties:


9.2. Get formatted time
You can select a variety of formats based on your requirements, but the simplest function to get a readable time pattern is asctime ():
2.1. Convert date to String

Preferred: Print time.strftime ('%y-%m-%d%h:%m:%s ');
Second: Print Datetime.datetime.strftime (Datetime.datetime.now (), '%y-%m-%d%h:%m:%s ')
Last: Print str (Datetime.datetime.now ()) [: 19]
2.2. Convert String to date

Expire_time = "2013-05-21 09:50:35"
D = datetime.datetime.strptime (Expire_time, "%y-%m-%d%h:%m:%s")
Print D;
9.3. Get Date Difference


Oneday = Datetime.timedelta (Days=1)
#今天, 2014-03-21
Today = Datetime.date.today ()
#昨天, 2014-03-20
Yesterday = Datetime.date.today ()-Oneday
#明天, 2014-03-22
Tomorrow = Datetime.date.today () + oneday
#获取今天零点的时间, 2014-03-21 00:00:00
Today_zero_time = Datetime.datetime.strftime (today, '%y-%m-%d%h:%m:%s ')

#0:00:00.001000
Print Datetime.timedelta (Milliseconds=1), #1毫秒
#0:00:01
Print Datetime.timedelta (Seconds=1), #1秒
#0:01:00
Print Datetime.timedelta (Minutes=1), #1分钟
#1:00:00
Print Datetime.timedelta (Hours=1), #1小时
#1 Day, 0:00:00
Print Datetime.timedelta (Days=1), #1天
#7 days, 0:00:00
Print Datetime.timedelta (Weeks=1)

9.4. Get time lag


#1 Day, 0:00:00
Oneday = Datetime.timedelta (Days=1)
#今天, 2014-03-21 16:07:23.943000
Today_time = Datetime.datetime.now ()
#昨天, 2014-03-20 16:07:23.943000
Yesterday_time = Datetime.datetime.now ()-Oneday
#明天, 2014-03-22 16:07:23.943000
Tomorrow_time = Datetime.datetime.now () + oneday
Note that time is a floating-point number, with milliseconds.

So to get the current time, you need to format it:
Print Datetime.datetime.strftime (today_time, '%y-%m-%d%h:%m:%s ')
Print Datetime.datetime.strftime (yesterday_time, '%y-%m-%d%h:%m:%s ')
Print Datetime.datetime.strftime (tomorrow_time, '%y-%m-%d%h:%m:%s ')

9.5. Get last day of last month

Last_month_last_day = Datetime.date (Datetime.date.today (). Year,datetime.date.today (). month,1)-datetime.timedelta (1)
9.6. The string date is formatted as a number of seconds, returning the floating-point type:

Expire_time = "2013-05-21 09:50:35"
D = datetime.datetime.strptime (Expire_time, "%y-%m-%d%h:%m:%s")
Time_sec_float = Time.mktime (D.timetuple ())
Print Time_sec_float
9.7, date formatted as seconds, return floating-point type:

D = Datetime.date.today ()
Time_sec_float = Time.mktime (D.timetuple ())
Print Time_sec_float
9.8, seconds spin string

Time_sec = Time.time ()
Print Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (TIME_SEC))

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.