Introduction to variables and data types in Python

Source: Internet
Author: User
Tags mathematical constants ord string methods uppercase letter

1. Variables and data types

1.1 Variables

1. Each variable stores a value-the information associated with the variable.

2. A variable can be not only an integer or a floating-point number, but also a string, which can be any data type.

Naming and use of 1.1.1 variables

Variable names can contain only letters, numbers, and underscores, and numbers do not begin. variable names cannot contain spaces, but you can use underscore intervals. The Python keyword and function name cannot be used as variable names. Variable names should be both brief and descriptive. Use the lowercase l and the capital Letter o sparingly, as they may be mistaken for numbers 1 and 0.

1.1.2 Avoid naming errors when using variables

When an error occurs, the interpreter provides a traceback (backtracking). Traceback is a record that points out where the trouble is.

1.2 String str

1. A string is a series of characters. is a data type that is quoted in Python as a string and can be quoted as a single quotation mark.

The 2.Unicode standard is also evolving, but the most common use is to represent a character in two bytes (4 bytes If you want to use very remote characters). Unicode is supported directly by modern operating systems and most programming languages. Converts the Unicode encoding to the UTF-8 encoding of "Variable length encoding".

3.Python data for bytes types is represented by single or double quotation marks with a b prefix: x = B ' ABC '. The STR represented in Unicode can be encoded as a specified bytes by using the Encode () method.

' ABC '. Encode (' ASCII ')

B ' ABC

Conversely, if we read the byte stream from the network or disk, then the data read is bytes. To turn bytes into STR, you need to use the Decode () method:

B ' ABC '. Decode (' ASCII ')

' ABC

4. For a single character encoding, Python provides an integer representation of the Ord () function to get the character, and the Chr () function converts the encoding to the corresponding character:

>>> Ord (' A ')

65

>>> Ord (' Middle ')

20013

>>> Chr (66)

B

>>> chr (25991)

Text

5. To calculate how many characters str contains, you can use the Len () function, the Len () function, to calculate the number of characters in Str, and the number of bytes if you switch to the Bytes,len () function. As can be seen, 1 Chinese characters are UTF-8 encoded and typically consume 3 bytes, while 1 English characters take up only 1 bytes.

1.2.1 Manipulation of strings

1. The method is the operation that Python can perform on the data.

2.title () displays each word in an uppercase letter, changing the initial letter of each word to uppercase.

3.upper () changes the string to all uppercase. Lower () changes the string to all lowercase.

4. If the string has at least one letter, and all letters are uppercase or lowercase, the isupper () and Islower () methods return the Boolean value True accordingly. Otherwise, the method returns False.

5.salpha () returns True if the string contains only letters and is not empty;

6.isalnum () returns True if the string contains only letters and numbers, and is not empty;

7.sdecimal () returns True if the string contains only numeric characters and is not empty;

8.sspace () returns True if the string contains only spaces, tabs, and line breaks, and is not empty;

9.istitle () returns True if the string contains only words that begin with an uppercase letter and are followed by lowercase letters.

The 10.startswith () and EndsWith () methods return True If the string they are calling starts or ends with the string passed in by the method. Otherwise, the method returns False.

The 11.join () method is called on a string, and the argument is a string list that returns a string.

>>> ', '. Join ([' Cats ', ' rats ', ' bats ')

' Cats, rats, bats '

>>> ". Join ([' My ', ' name ', ' is ', ' Simon '])

' My name is Simon '

>>> ' ABC '. Join ([' My ', ' name ', ' is ', ' Simon ')

' Myabcnameabcisabcsimon '

The 12.split () method does exactly the opposite: it returns a list of strings for a string call. You can also pass in a split string to the Split () method, specifying that it is split by a different string.

>>> ' My name is Simon '. Split ()

[' My ', ' name ', ' is ', ' Simon ']

The 13.rjust () and Ljust () string methods return the populated version of the string that invokes them, aligning the text by inserting an empty glyd. The first parameter of these two methods is an integer length that is used to align the string. The Second optional parameter of the Rjust () and Ljust () methods will specify a fill character, replacing the space character.

>>> ' Hello '. Rjust (20, ' * ')

' ***************hello '

>>> ' Hello '. Ljust (20, '-')

' Hello---------------'

The 14.center () string method is similar to Ljust () and Rjust (), but it centers the text instead of left or right alignment.

15.sort () sorts the strings.

16. It is important to note that the Python program is case-sensitive , and if the case is written incorrectly, the program will give an error.

17. Merge--python use Plus + to combine strings

  1. first_name = "Ada"

  2. last_name = "Lovelace"

  3. Full_name = first_name + "" + last_name

  4. Print (Full_name)

  5. Ada Lovelace

18. You can add R to the quotation mark at the beginning of the string to make it the original string. The original string completely ignores all escape characters and prints out all the backslashes in the string.

>>> print (R ' s is Carol\ 's cat.)

That's carol\ ' s cat.

19. Delete Blank: Method Rstrip () right Lstrip () left strip () on both sides

syntax error: An error that is encountered from time to time, in a string enclosed in single quotation marks, which causes an error if it contains an apostrophe. Double quotes do not.

21.Print () to print, the comma will empty one cell.

The 22.pyperclip module has the copy () and paste () functions, which can send text to or receive text from the computer's clipboard.

23. The string has a replace () method

>>> a = ' abc '

>>> a.replace (' A ', ' a ')

' ABC '

1.2.2 Null value

The null value is a special value in Python, denoted by none. None cannot be understood as 0, because 0 is meaningful, and none is a special null value.

1.2.3 Constants

Constants are immutable variables, such as the usual mathematical constants π is a constant. In Python, constants are typically represented in all uppercase variable names: PI = 3.14159265359

1.2.4 Assignment Value

In Python, equals = is an assignment statement that assigns any data type to a variable, the same variable can be repeatedly assigned, and can be a variable of different types:

A = 123 # A is an integer

Print (a)

A = ' ABC ' # A becomes a string

Print (a)

Assignment statement: A, B = B, A + b

t = (b, A + b) # T is a tuple

A = T[0]

b = t[1]

1.2.5 Formatting

There are two types of formatting in Python, the first is implemented in%, and the second is in the format of {} format.

' Hello,%s '% ' world '

The% operator is used to format the string. Inside the string,%s is replaced with a string,%d is replaced with an integer, there are several% placeholder, followed by a number of variables or values, the order to correspond well. If there is only one %? , the parentheses can be omitted. Common placeholders:

%d integers

%f floating Point

%s string

%x hexadecimal integer

where formatted integers and floating-point numbers can also specify whether to complement 0 and the number of digits of integers and decimals:

>>> '%2d-%02d '% (3, 1)

' 3-01 '

>>> '%.2f '% 3.1415926

' 3.14 '

If you're not sure what to use,%s will always work, and it will convert any data type to a string.

In some cases, the% inside the string is an ordinary character, which needs to be escaped and expressed as a% by percent.

The second formatting method, format, is replaced by the {} instead of%.

1. Normal use

>>> print ("My Name {}, this year {} years old". Format ("Xiao Li", 20))

My name is Xiao Li, 20 years old this year.

2. You can also change the order of formatting by filling in the numbers in parentheses

>>> Print ("I'm {1}, this year {0} years old". Format ("Xiao Li", 20))

My name is 20, and this year Xiao Li is old.

3. Take the variable by key

>>> print ("My Name {name}, this year {age}". Format (name= "Xiao Li", age=20))

My name is Xiao Li, 20 years old this year.

1.2.6 Escape character

Blank-refers to any nonprinting characters, such as spaces, tabs, and line breaks.

Escape character \ can escape many characters \ t tab \ n line break

The character \ itself is also escaped, so the character \ \ is represented by \ \

If there are many characters in the string that need to be escaped, Python can use R ' ' to indicate that the string inside of ' is not escaped by default:

>>> print (' \\\t\\ ')

\ \

>>> print (R ' \\\t\\ ')

\\\t\\

1.3 Numbers

1.3.1 Integer int

can be arithmetic.

Computer because of the use of binary, so, sometimes hexadecimal notation is more convenient, hexadecimal with 0x prefix and 0-9,a-f, such as: 0XFF00,0XA5B4C3D2, and so on.

The division of integers is precise. In Python, there are two kinds of division, a division is/,/division evaluates to a floating-point number, even if it is exactly divisible by two integers, the result is also a floating-point number. There is also a division is//, called the floor except, the division of two integers is still an integer.

% takes the remainder.

1.3.2 Floating point Float

Python, which is called a floating-point number, is called a float, because the decimal point position of a floating-point number is variable when represented by scientific notation, for example, 1.23x109 and 12.3x108 are exactly equal.

For very large or very small floating-point numbers, it must be expressed in scientific notation, the 10 is replaced with E, 1.23x109 is 1.23e9, or 12.3e8,0.000012 can be written 1.2e-5, and so on.

1.3.3 using function str () to avoid errors

Data type checking can be implemented with built-in function isinstance ():

def my_abs (x):

If not isinstance (x, (int, float)):

Raise TypeError (' bad operand type ')

If x >= 0:

return x

Else

Return-x

1.4 Notes

1. The statement that begins with # is a comment, the comment is visible to the person, can be any content, and the interpreter ignores the comment. Each of the other lines is a statement that, when the statement ends with a colon:, the indented statement is treated as a block of code.

#。。。。。。

2. Because the Python source code is also a text file, so when your source code contains the Chinese language, when you save the sources, you need to be sure to specify Save as UTF-8 encoding. When the Python interpreter reads the source code, in order for it to be read by UTF-8 encoding, we usually write these two lines at the beginning of the file:

#!/usr/bin/env Python3

#-*-Coding:utf-8-*-

3. Comment "" "" of the document string

Zen of 1.5Python

The Zen of Python, by Tim Peters

  1. Beautiful is better than ugly.

  2. Explicit is better than implicit.

  3. Simple is better than complex.

  4. Complex is better than complicated.

  5. Flat is better than nested.

  6. Sparse is better than dense.

  7. Readability counts.

  8. Special cases aren ' t special enough to break the rules.

  9. Although practicality beats purity.

  10. Errors should never pass silently.

  11. Unless explicitly silenced.

  12. In the face of ambiguity, refuse the temptation to guess.

  13. There should is one--and preferably only one--obvious the-do it.

  14. Although that is obvious at first unless you ' re Dutch.

  15. Now is better than never.

  16. Although never is often better than *right* now.

  17. If the implementation is hard to explain, it's a bad idea.

  18. If the implementation is easy to explain, it could be a good idea.

  19. Namespaces is one honking great idea – let's do more than those!

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.