Python base (2): The basic data types Operation

Python is an interpreted language, it has the advantage code is simple and easy to understand, a large number may be required by the daily operation has a good built-in method and packaging method of the third party to complete the module.

 

String

  • index

Starting at index 0 (the number of front to back), the lower end labeled 1 (from the number of forward)

= str_a ' Hello Python ' 
Print (str_a [0]) # print result: H
 Print (str_a [-1]) # print result: n
  • slice

Format: [start position: end position: step], the default step size of 1

= str_a ' Hello Python ' 
Print (str_a [0: 12 is:. 3]) # print result: hlph
  • splice

There are two methods stitching strings, first: str1 + str2 second: ',' join ((str1, str2)), the parameters in the join method is an iterative type of data.

= str_a ' Hello ' 
str_b = ' Python ' 
Print (str_a + str_b) # print result: hellopython
 Print ( ' , ' .join ((str_a, str_b))) # print result: hello, python
  • Formatted output

Python string, there are three ways of formatting the output:

1, the conventional method for formatting:%

% S: placeholder character (of any type)

% D: a numeric type placeholder

% F: floating point number placeholder, the default retention six decimal places

Print ( ' I am% S ' % ' Bob ' ) # print the results: I am Bob
 Print ( ' year% d years old ' % 24 ) # print the results: This year, 24-year-old
 Print ( ' Height% .2f ' % 1.7381) # Print results: height 1.74

2, format formatted output

{} String for the number, the number can be in the format of incoming data are sequentially filled; and format parameters may be more than the number of {}, but not less to avoid an error

str_a = Hello everybody, my name is {}, {} years old this year
 Print (str_a.format ( ' Bob ' , 18 )) # print the results: Hello everyone, I called the Little Ming, 18 years old
 # reserved digits after the decimal point 
Print ( ' today pork price {:} .2f element ' .format (28.623)) # print result: today is the price of pork 28.62 yuan # fractional percentage displayed in the form Print ( ' percentage {: 0.2%} ' . format (0.34)) # print the results: percentage 34.00%

3, the expression F

= name ' red ' 
Age = 18 
S3 = F. ' My name {name}, Age Age} { ' 
Print (S3) # print result: I red name, age 18

 

  • Common methods:

find (parameter 1, parameter 2): Find the start index of the string in the string segment that occurs, a parameter indicating a start position to find a string that represents a lookup parameter 2, if the string is not found is returned -1

= str_a ' 123abc456def '  
RES = str_a.find ( ' C ' results, 3) #res of 5

replace (parameter 1, parameter 2, parameter 3): specified string with fragment 1 represents the number of parameters to replace the string fragment, fragment string after replacement parameter represents 2, 3 parameter specifies an alternative (default Replaces all of)

= str_a ' 123abc456def456456 ' 
RES = str_a.replace ( ' 456 ' , ' 789 ' , 2) as a result #res 123abc789def789456

split (parameter 1, parameter 2): specify the split point to split the string parameter represents the dividing point 1, 2 split times specified parameters (default find all the split point and your split)

= str_a ' 123abc456def456abc456 ' 
RES = str_a.split ( ' ABC ' results, 1) #res for [ '123', '456def456abc456' ]

count (): the number of segments appear statistical character string in the string, the number of statistical substring occurring, returns 0 if there

= str_a ' 123abc456def456abc456 ' 
RES = str_a.count ( ' 456 ' results) #res is 3

upper (): the lowercase letters to uppercase letters

= str_a ' 123aBc456DeF456Abc456 ' 
RES results = str_a.upper () #res is 123ABC456DEF456ABC456

lower (): uppercase letters lowercase letters

= str_a ' 123aBc456DeF456Abc456 ' 
RES results = str_a.lower () #res is 123abc456def456abc456

A built-in string above methods, there are many other ways, for example: title (), capitalize (), swapcase (), etc.

 

Lists, tuples and strings, are data types may be iterative, they support indexing and slicing operations, no more repeated here. Further more, compared to the list of tuples obtained with richer operation space, as queues, stacks, heap data structures, and also a list of a relationship. So the list of common and what does it work?

We add elements to the list:

= list_a [1, 9, 6, 3, 1,. 4,. 5 ] 
# add an element to the end of the list list_a.append (
. 7 ) Print (list_a) #list_a result is: [1, 9, 6, 3, 1, 4, 5, 7]
# insert an element to the list (parameter 1: the subscript index, parameter 2: value)
list_a.insert (
5,. 8 ) Print (list_a) #list_a result is: [1, 9, 6, 3, 1, 8, 4, 5, 7]
# add more elements (types of data may be iteratively) in the end of the list
list_a.extend ([
2, 3 ]) Print (list_a) #list_a result is: [1, 9 , 6, 3, 1, 8, 4, 5, 7, 2, 3]

At the same time the list of methods to remove elements also has a variety of:

remove: element (the first element found deleted) delete the specified

pop: the specified index position to delete (delete the default index is not specified when the last one)

Empty the list of all the elements: clear

Sort by:

sort

list_a = [1, 9, 6, 3, 1, 4, 5]
list_a.sort()
print(list_a)  #list_a结果为:[1, 1, 3, 4, 5, 6, 9]

sorted

list_a = [1, 9, 6, 3, 1, 4, 5]
list_b = sorted(list_a)
print(list_b)  #list_b结果为:[1, 1, 3, 4, 5, 6, 9]

and default sort are sorted in ascending order, their biggest difference is that sort the list itself is sorted, and the sort method does not return value, and returns a value sorted, there must be a variable receiving a result, the list itself is not sorted.

In addition there are reverse reverse (), count the number of statistical elements appear (), find the element index index (), empty clear () methods.

 

dictionary

Add elements to the dictionary:

dict_1 = { ' AA ' : 8888, ' BB ' : 22 is, ' CC ' : 33 is } 
dict_1 [ ' dd ' ] = 44 is
 Print (dict_1) # print result: { 'aa': 8888, 'bb': 22, 'cc': 33, 'dd ': 44}

Add the elements above this way, if the key does not exist in the dictionary, it will add a new key-value pairs, otherwise it will modify the value corresponding to the key

To increase the number of elements in the dictionary:

= {dict_1 ' AA ' : 8888, ' BB ' : 22 is, ' CC ' : 33 is } 
dict_1.update ({ ' C ' :. 1, ' D ' :. 1 })
 Print (dict_1) # print result: { 'aa ': 8888,' bb ': 22,' cc ': 33,' c ': 1,' d ': 1}

Delete dictionary there are several methods:

  • To delete the key by key:  dict_1.pop ( ' CC ' )
  • Delete the end of a key-value pair dictionary:  dict_1.popitem ()
  • Key to delete an arbitrary position of:  del dict_1 [ ' BB ' ]

Dictionary of query method:

  • By lookup key: dict_1 [ ' AA ' ] or dict_1.get ( 'aa')
  • Gets a dictionary of all the key: List (dict_1.keys ())
  • Get all the values in the dictionary: List (dict_1.values ())
  • Gets a dictionary of all the key-value pairs: List (dict_1.items ())

Empty dictionary:  dict_1.clear () 

 

Some types of data conversion operations include:

String transfer list:  List ( ' Python ' ) 

List to String:

''.join(['h', 'e', 'l', 'l', 'o'])

Dictionary transfer list:  dict (ZIP ([ ' A ' , ' B ' ], [. 1, 2])) 

Can be interchangeable among the various types of data, there is not one by one example.

 

Special episode knowledge: This module introduces a guarantee decimal floating point precision, if you want to ensure that the results have a float in the calculation involved in precision is not lost, then the decimal comes in handy, specific use is as follows,

Print (0.1 + 0.11) Print Results: 0.21000000000000002

As can be seen more clearly in question the accuracy of the results, the problem lies in the 0.1 binary infinite loop in the computer, the excess part will be intercepted, will eventually lead to loss of precision occurs under certain operational conditions, how to use the decimal avoid it, as follows:

from decimal Import Decimal
 Print (Decimal (str (0.1)) + Decimal (str (0.11))) # print the results: 0.21

Consider using this numerical method in the scientific computing or monetary terms, it is generally not recommended because this method of calculation efficiency is lower than the floating-point calculations.

Guess you like

Origin www.cnblogs.com/suanmiaoup/p/12161045.html
Recommended