Python Basic data type

Source: Internet
Author: User

Basic data types for Python3
    • Variables do not need to be declared in advance
    • Each variable must be assigned before it can be created after assignment.
    • In Python, a variable is of no type, and the word "type" here refers to the type of image stored in memory.
    • There are six standard data types in Python
      • Number (numeric)
      • String (String)
      • List (lists)
      • Tuple (tuple)
      • Dictionary (dictionary)
      • Sets (collection)
      • Immutable: Number (numeric), string (string), tuple (tuple)
      • Variable: list, Dictionary (dictionary), set (collection)
1. Number
  • Common types are int, float, bool; You can use the type () function to view variable types
  • int, float supports all arithmetic operations
  • BOOL type 0 and 1,0 equivalent to false,1 to True
  • Example: for an int, float type operation:

            a = 8            b = 3        a + b    # 11        a - b     # 5        a * b    # 24        a // b   # 2        a / b    #  2.6666666666666665        a % b  # 2        a ** b  # 512
  • Example: type bool:
    In []: a = 0
    In [23°c]: b = 1
    In []: a = = True
    OUT[24]: False
    in [+]: a = = False
    OUT[25]: True
    in [+]: b = = True
    OUT[26]: True
    in [+]: b = = False
    OUT[27]: False2. String
  • Define the method: a = ‘abc‘ ora = str()
  • Common ways to manipulate strings: index, find, slice, add, copy, output
  • common methods for strings
    • Example: string multiplication (copy)
        ' 8 ' * 8  

      #字符串相加
      name = ' Yhyang '
      city = ' Beijing '
      infor = name + ' + City
      #字符串索引
      Name[0] # Returns the first value: Y
      Name[-1] # returns the last value: G
      #字符串切片
      name[:] #: Do not write around, take the entire string
      name[0:3] # from the first to the 4th, do not take fourth: Yhy
      Name[:-1] # from the first to the penultimate: Yhyan
      #字符串输出, output
      print (f ' name: {name}, City: {'} ' in the F ' format) The
      Output is: Name: Yhyang, City: Beijing
      #字符串常用方法:
      Name.upper () # to capitalize the value of name, and lowercase to name.lower ()
      Info.title () # Title style, capitalize the first letter of each word
      Name.strip (' h ') # Remove header, tail specified string
      Info.capitalize () # Capitalize the first letter of the string
      Name.replace (' y ', ' y ') # Replace Y with y
      Name.zfill (10) # String right-aligned, not enough 10-bit with 0 completion
      Name.rjust (10, ' $ ') # string right-aligned, not enough 10-bit with $ to complement full
      Name.center (10, ' $ ') # String middle alignment, not enough 10 bits to complete the
      Name.count (' y ') # to calculate the number of Y in the string
      Name.index (' A ') # returns the position of a in the string, if there are multiple, returns the position of the first
      Name.find (' Hy ') # Find Hy in the string position
      Info[1:6:2] # Take the string second to sixth, the step is 2, take an interval of one
      Info[::-1] # return to the string
      Info.split (' y ') # with Y as the delimiter, separating the string

      3. List
  • List Definition method: a = [] ora = list()
  • List element type: numeric, string
  • List operation mode: Add, delete, change, check, reverse, add
    • Example Definition List
       a = [‘zhangsan‘, ‘lisi‘, ‘wangwu‘] b = [1, 3, 2, 5, 4] #元素类型 注:虽然一个列表中的元素可以有字符串,和数值 但是,不建议定义字符串时混着用,建议一个字符串中只有一种数据类型 #操作方式 a.append(‘yhy‘)                     # 增加列表元素,新元素在最后面追加 a.insert(2, ‘e‘)                        # 在列表第三个位置插入值e a.pop(n)                                # n为数值,删除列表中第n个元素,参数为空时从最后一个删除 a.[::-1]                                   # 反转列表 a.reverse()                            # 反转列表 a[3]                                        # 取列表中第四个元素的值 a[-1]                                       # 取列表中倒数第一个元素的值 a[1:3]                                     # 取列表中第二到第3个元素的值 a[1] = ‘aaa‘                             # 修改列表第二个元素的值 a = []                                      # 清空列表
      4. Tuples
  • Tuple (tuple) is similar to a list, except that the elements of a tuple cannot be modified. Tuples are written in parentheses (), and the elements are separated by commas.
  • The element types in a tuple can also be different
    • Define the way: a = () orb = tuple()
    • Operate in a similar way to a list
    • Common methods: Take the maximum minimum value
          max(a)                                # 取元组a中最大值    min(a)                                 # 取元组a中最小值    len(a)                                  # 查看元组的长度    #元组相加    a + b                                  # 元组a与元组b的值组成一个新的元组
      5. Dictionaries
  • The Dictionary (dictionary) is another very useful built-in data type in Python
  • A list is an ordered collection of objects, and a dictionary is an unordered collection of objects
  • The elements in the dictionary are accessed by keys.
  • The dictionary is defined by {}, which is a set of set of key-value pairs, key:value
  • The key is unique, immutable
    • Example: dictionary definition
          DIC = {} or dic = Dict () dic = Dict (' Runoob ', 1), (' Google ', 2), (' Taobao ', 3)]) print (DIC) output {' Taobao ': 3, ' Runoob ': 1, ' Google ': 2} {x:x**2 for x in (2, 4, 6)} Generate dictionary {2:4, 4:16, 6:36} dic = Dict (runoob=1, google=2, Taoba                        O=3) DIC has a value of {' Taobao ': 3, ' Runoob ': 1, ' Google ': 2} #字典取值 value dic[' Taobao ' in the way dic[' key '] # value is 3 for Key,value in Dic.items (): Print (f ' {key}:{value} ') # Key:vlaue #字典的相关方法 dic with a For loop output dictionary.                  Clear () # Delete all elements within the dictionary dic.copy () # Returns a dictionary of shallow copy dic (). Fromkeys ()                          # Create a new dictionary with the sequence SEQ element as the dictionary key, Val for the dictionary key corresponding to the value Dic.get () # Returns the value of the specified key key in DIC                          # returns True if the key is in the dictionary, otherwise False Dic.items () # Returns the traversed tuple in the inside Dic.keys () # Returns a dictionary with a list of all keys Dic.values () # Returns all values in the dictionary in the list Dic.setdefault (key,default) # and GE T () like, if the key does not exist in the dictionary, add the key and set the value toDefault Dic.pop (key) # Deletes the value of the specified key key and returns the value 
      6. Collection
  • A sequence of unordered, non-repeating elements
  • The basic function is to test the membership and remove duplicate elements
  • You can use the curly braces {} or the set () function to define the collection
  • Note: Creating an empty collection must be set (), not {}, because {} is an empty dictionary
  • Set can perform set operations
    • Example: Creating a format
           s = {‘Tom‘, ‘Jim‘, ‘Mary‘, ‘Tom‘, ‘Jack‘, ‘Rose‘}     或 s = set((‘Tom‘, ‘Jim‘, ‘Mary‘, ‘Tom‘, ‘Jack‘, ‘Rose‘))     或 s = set([‘Tom‘, ‘Jim‘, ‘Mary‘, ‘Tom‘, ‘Jack‘, ‘Rose‘])     得到的s是一样的     #集合运算     a=set(‘abcdefgabcdefg‘)     b=set(‘acbcdc‘)     print(a - b)                        # a和b的差集     print(a | b)                        # a和b的并集     print(a & b)                       # a和b的交集     print(a ^ b)                        # a和b不同时存在的元素
  • Use s.add(key) can add elements to the collection, can be added repeatedly, but no effect
  • Use s.remove(key) to delete elements
  • Note that the variable Object 7 cannot be placed in the collection. Data type conversions
function Description
int (x [, Base]) Convert x to an integer
Float (x) Convert x to a floating-point number
Complex (real [, Imag]) Create a complex number
STR (x) Convert an object x to a string
REPR (x) Convert an object x to an expression string
eval (str) Used to evaluate a valid Python expression in a string and return an object
Tuple (s) Converting a sequence s to a tuple
List (s) Convert the sequence s to a list
Set (s) Convert to mutable Collection
Dict (d) Create a dictionary. D must be a sequence (key,value) tuple
Frozenset (s) Convert to immutable Collection
Chr (x) Converts an integer to one 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 an octal string

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.