Python Basic data type

Source: Internet
Author: User

Python Basic data type


1. String

str1= "ABCDEFGH"

Str2= ' Jkdjs '

The Python string list has 2 order of values:

Left-to-right index starts at default 0, with a maximum range of 1 less string lengths

Right-to-left index starts with default-1, the maximum range is the beginning of the string

If you want to implement a string to get a string, you can use the variable [header subscript: tail subscript], you can intercept the corresponding string, where the subscript is starting from 0, can be positive or negative, subscript can be null to take the head or tail. s = ' Ilovepython ', s[1:5] The result is Love


String operators

+ String connection

* Duplicate output string

[] get the characters in a string by index >>>a[1]

[ : ] Intercept part of a string >>>a[1:4]

In member operator-returns TRUE if the string contains the given character

Not in member operator-returns TRUE if the string does not contain the given character

% format string


Built-in functions


Str.count (sub[, start[, end]])

Returns the number of times the substring of a range [start,end] does not overlap. Optional parameters start and end are interpreted as slicing notation

Str.decode ([encoding[,errors]])

Returns the encoded version of the string as a byte object. The default encoding is ' Utf-8 '

Str.endswith (suffix[, start[, end]])

Returns True if the string ends with the specified suffix, otherwise False. The suffix can also be a tuple suffix to find

Str.find (Sub [Sub,start [, end]])

Returns the smallest index in a string, where substring is found in the slice s[start:end]. An optional parameter, start and end, is interpreted as a slicing notation. If no sub is found return-1


Str.format (Sub [, Start [, end]])

formatting strings

Str.isalnum (...)

Returns true if all characters in the string are alphanumeric and has at least one character, otherwise false

Str.isalpha (...)

Returns true if all characters in the string are letters and at least one character, otherwise false

Str.islower (...)

Returns true if all contained characters in the string are lowercase and at least one socket character, otherwise false


Istitle (...)

Whether the opening letter is uppercase

Isupper (...)

Whether the string is uppercase

Str.join (...)

Returns a string that is a concatenated string in an iterative iteration

Str.ljust (...)

A string that returns the length width of the left-aligned string. Fills with the specified Fillchar

Lower (...)

Returns a copy of a string, all containing characters converted to lowercase

Lstrip (...)

Returns a copy of a string with a leading character. The chars parameter is a string that specifies the character set to delete. If the omit or none,chars parameter defaults to remove spaces

Str.partition (Sep)

Splits the first occurrence of Sep into a string and returns a 3-tuple of the part that contains the delimiter before the delimiter itself and the portion after the delimiter. Returns a 3-tuple containing the string itself, followed by two empty strings, if no delimiter is found

RFind (...)

Find from the right of the string

Rindex (...)

Returns the index position of the string, starting from the right of the character

Str.rjust (...)

A string that returns the length width of the right-aligned string. Fills with the specified Fillchar

Rstrip (...)

Delete the right space of a string

Str.split (Sep = none,maxsplit =-1)

Returns a list of words in a string, using Sep as the delimiter string. If Maxsplit is given, a maximum of Maxsplit splits are performed (therefore, the list can have up to maxsplit+1 elements). If Maxsplit or-1 is not specified, there is no limit on the number of splits (all can be split).

Splitlines ([keepends]) returns a list of rows in a string that is broken at the line boundary. NewLine characters are not included in the results list unless Keepends is true and true


Str.strip ([chars]) returns a copy of the leading and trailing characters of the string deleted. The chars parameter is a string that specifies the character set to delete. If you omit or none,chars the parameter, the whitespace is removed. The character parameter is not a prefix or suffix; Instead, all combinations of its values are stripped

Upper (...)

Convert Letters to uppercase

Title (...)

First letter uppercase, remaining lowercase

Str.capitalize ()

First letter uppercase, other lowercase letters

Str.replace (",")

Returns true if there is only a space character in the string and has at least one character, otherwise false

Str.isprintable ()

Returns true if all characters in the string are printable or the string is empty, otherwise false

Str.zfill (width)

Returns a copy of a string that fills the ASCII ' 0 ' number to form a width-length string

Str.join (...)

Adding elements to a queue is the inverse method of Split


2. List

List, which is a container that can contain arbitrarily ordered sets, mutable objects

Support for heterogeneous: the same object can be stored in numbers, strings of multiple data types

A list can accomplish the data structure implementation of most collection classes. It supports characters, numbers, strings that can even contain lists (so-called nesting), and data items do not need to have the same type

The list of values can also be used to split the variable [head subscript: Tail subscript], you can intercept the corresponding list, from left to right index default 0, starting from right to left index default-1, subscript can be empty to take the head or tail.

The plus sign (+) is the list join operator, and the asterisk (*) is a repeating operation

member Relationship judgment: in Not in

definition list: alis=[' A ', ' C ', ' B ', ' A ', ' e ', ' r ', ' t ', ' Q ']

operator: the plus sign (+) is a list join operator, and an asterisk (*) is a repeating operation


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.


Python has 6 built-in types of 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.


List Functions & Methods

CMP (List1, List2) compares two elements of a list

Len (list) List element number

Max (list) returns the maximum value of the listing element

MIN (list) returns the minimum value of the list element

List (seq) converts tuples to lists


Built-in functions


Count (obj)

Count the number of occurrences of an element in a list

Extend (SEQ)

Append multiple values from another sequence at the end of the list (extend the original list with a new list)

Index (OBJ)

Index index find out a value from the list where the first occurrence of a match is indexed

Insert (Index,obj)

Append a value after an index, insert the object into the list

Pop (...)

Query the value of list by index if the parameter is not passed by default to the last value of list

Remove (...)

Remove delete [Delete specified value remove (\ ' value required to remove \ ')]

Reverse (...)

Invert, reverse list of elements

Sort (...)

Sort

Append (...)     

Append append [append to Last of list]

Copy (...)

Copy, Deepcopy deep copy

3, meta-group

A tuple is another data type, similar to a list.

The tuple is identified with a "()". The inner elements are separated by commas. But tuples cannot be modified, equivalent to read-only lists.

Tuples are similar to strings, and subscript indexes start at 0 and can be intercepted, combined, etc.

Tuples are not allowed to be updated. And the list is allowed to be updated

Built-in functions

Count (...)

Returns the number of tuple members

Index (...)

Returns the offset position of a member in a tuple

CMP (Tuple1, Tuple2)

Compares two tuples of elements.

Len (tuple)

Calculating the number of tuple elements

Max (tuple)

Returns the maximum value of an element in a tuple

MIN (tuple)

Returns the element minimum value in a tuple

Tuple (SEQ)

Convert a list to a tuple


4. Dictionaries

The Dictionary (dictionary) is the most flexible built-in data structure type in Python, except for lists. 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, not by offsets.

The dictionary is identified with "{}". A dictionary consists of an index (key) and a value corresponding to it.


Dictionary dict: [key:vlues] | ---{"x": "1", "Y": "2"}

Factory function dict:dict (Zip (' x ', ' Y '), (' 1 ', ' 2 '))

The zip function merges two lists into a list of tuples, which are ignored when two lists are not the same length.

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

The difference between a dictionary type and a sequence type:

1. Access to and access to data differs in different ways.

2. The sequence type only uses the key of the numeric type (indexed in numerical order from the beginning of the sequence);

3. The mapping type can be used as a key for other object types (e.g. numbers, strings, ganso, usually strings as keys), and the keys of the sequence type are different, the key of the mapping type is straight

4. Directly or indirectly associated with stored data values.

5. The data in the mapping type is unordered. This is not the same as the sequence type, and the sequence type is numerically ordered.

6. The mapping type is directly "mapped" to a value with a key.

7. The key must be unique, but the value does not have to be

Characteristics:

1, the key and the value with the colon ":" separate;

2, the term and the item with a comma "," separate;

3. The keys in the dictionary must be unique, and the values may not be unique


Create a dictionary

Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '};


Accessing values in the dictionary

Print dict[' Alice ']

dict[' Beth ']


Modify Dictionary

Dict[' age '] = 8


Delete a dictionary element

Del dict[' Name ']; # Delete key is ' Name ' entry

Dict.clear (); # Empty Dictionary all entries

Del Dict; # Delete Dictionary



Dictionary built-in functions & methods

CMP (Dict1, DICT2) Comparison of two dictionary elements

Len (dict) calculates the number of dictionary elements, that is, the total number of keys

STR (dict) output dictionary printable string representation

Type variable returns the type of the input variable, if the variable is a dictionary

ITER (dict) returns an iterator to the key, value, or item (expressed as a tuple) in the dictionary. (Key, value)


Built-in functions


Iteritems (...)


Iterkeys (...)


Itervalues (...)


Keys (...)

Returns the dictionary all keys

Pop (key [, default])

If key is in the dictionary, delete it and return its value, otherwise the default value is returned. If no default value is given and the key is not in the dictionary, Keyerror throws a

Popitem (...)

Removes from the dictionary and returns any pairs. (key, value) \ Popitem () is useful for destructive iterations of a dictionary that is used frequently in a collection algorithm. If the dictionary is empty, call Popitem () to raise a keyerror.

VALUES (...)

Return all values in the dictionary

Radiansdict.clear ()

Delete all elements in a dictionary

Radiansdict.copy ()

Returns a shallow copy of a dictionary

Radiansdict.fromkeys ()

Create a new dictionary with the keys to the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary

Radiansdict.get (Key, Default=none)

Returns the value of the specified key if the value does not return the default value in the dictionary

Radiansdict.has_key (Key)

Returns False if the key returns true in the dictionary Dict

Radiansdict.items ()

Returns an array of traversed (key, value) tuples as a list

Radiansdict.keys ()

Returns a dictionary of all keys in a list

Radiansdict.setdefault (Key, Default=none)

Similar to get (), but if the key does not exist in the dictionary, the key is added and the value is set to default

Radiansdict.update (DICT2)

Update the key/value pairs of the dictionary dict2 to the Dict

Radiansdict.values ()

Returns all values in the dictionary as a list


5. Slicing

A, String slicing

str = ' Hello world! '

Print str # output full string

Print Str[0] # The first character in the output string

Print Str[2:5] # The string between the third and fifth in the output string

Print str[2:] # Outputs a string starting from the third character

Print str * 2 # output String two times

Print str + "TEST" # Output concatenated string

B, List slices

list = [' Runoob ', 786, 2.23, ' John ', 70.2]

Tinylist = [123, ' John ']

Print List # output complete listing

Print List[0] # The first element of the output list

Print List[1:3] # outputs the second to third element

Print list[2:] # Outputs all elements from the third start to the end of the list

Print tinylist * 2 # Output List two times

List of print List + tinylist # printing combinations

C, tuple slices

tuple = (' Runoob ', 786, 2.23, ' John ', 70.2)

Tinytuple = (123, ' John ')

Print tuple # output full tuple

Print Tuple[0] # The first element of an output tuple

Print Tuple[1:3] # outputs the second to third element

Print tuple[2:] # Outputs all elements from the third start to the end of the list

Print Tinytuple * 2 # output tuple two times

Print tuple + tinytuple # Printing Group of tuples

6. Data type Conversion

int (x [, Base]) converts x to an integer

Long (x [, Base]) converts x to a long 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

Tuple (s) converts a sequence s to a tuple

List (s) converts the sequence s to a list

Set (s) is converted to a mutable set

Dict (d) Create a dictionary. D must be a sequence (key,value) tuple.

Frozenset (s) converted to immutable collection

Chr (x) converts an integer to one character


Python Basic data type

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.