Comparison with list and str of Python

Source: Internet
Author: User
The list and str types of data have many similarities and are quite different. In this article, we will make a brief comparison between them and review the previous knowledge about the two ". Similarities

All data belongs to the sequence type

The so-called sequence data means that each element of a sequence can be obtained by specifying a number and the line is called an offset. to get multiple elements at a time, you can use slices. The offset starts from 0 and the total number of elements decreases by 1.

For example:

>>> welcome_str = "Welcome you">>> welcome_str[0]'W'>>> welcome_str[1]'e'>>> welcome_str[len(welcome_str)-1]'u'>>> welcome_str[:4]'Welc'>>> a = "python">>> a*3'pythonpythonpython'>>> git_list = ["qiwsir","github","io"]>>> git_list[0]'qiwsir'>>> git_list[len(git_list)-1]'io'>>> git_list[0:2]['qiwsir', 'github']>>> b = ['qiwsir']>>> b*7['qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir']

For such data, the following operations are similar:

>>> First = "hello, world" >>> welcome_str 'welcome you' >>> first + "," + welcome_str # connect str 'Hello, world, welcome you '>>> welcome_str # The original str is not affected, that is, after the plus sign is connected, a new string 'welcome you' is generated. >>> first 'Hello, world '>>>> language = ['Python'] >>> git_list ['qiwsir', 'github ', 'io ']> language + git_list # connect to the list with the + sign to obtain a new list ['Python', 'qiwsir', 'github ', 'io'] >>> git_list ['qiwsir ', 'github', 'io'] >>> language ['Python'] >>> len (welcome_str) # get the number of characters 11 >>> len (git_list) # get the number of elements 3

Differences

The biggest difference between list and str is that list can be changed from the original position, while str cannot be changed from the original position. How can this be understood?

First, let's take a look at these operations on the list. the feature is that the list is modified in the original place:

>>> git_list['qiwsir', 'github', 'io']>>> git_list.append("python")>>> git_list['qiwsir', 'github', 'io', 'python']>>> git_list[1]        'github'>>> git_list[1] = 'github.com'>>> git_list['qiwsir', 'github.com', 'io', 'python']>>> git_list.insert(1,"algorithm")>>> git_list['qiwsir', 'algorithm', 'github.com', 'io', 'python']>>> git_list.pop()'python'>>> del git_list[1]>>> git_list['qiwsir', 'github.com', 'io']

If the preceding operations are used on str, an error is reported, for example:

>>> welcome_str'Welcome you'>>> welcome_str[1] = 'E'Traceback (most recent call last):File "
 
  ", line 1, in 
  
   TypeError: 'str' object does not support item assignment>>> del welcome_str[1]Traceback (most recent call last):File "
   
    ", line 1, in 
    
     TypeError: 'str' object doesn't support item deletion>>> welcome_str.append("E")Traceback (most recent call last):File "
     
      ", line 1, in 
      
       AttributeError: 'str' object has no attribute 'append'
      
     
    
   
  
 

If you want to modify a str, you have.

>>> Welcome_str 'welcome you' >>> welcome_str [0] + "E" + welcome_str [2:] # generate a new str 'welcome you' >>> welcome_str # it has no effect on the original 'welcome you'

In fact, in this way, it is equivalent to a new str.

Multi-dimensional list

This is also the difference between the two, although a little far-fetched. In str, each element can only be a character. in list, an element can be any type of data. We can see numbers or characters as follows:

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]>>> matrix[0][1]2>>> mult = [[1,2,3],['a','b','c'],'d','e']>>> mult[[1, 2, 3], ['a', 'b', 'c'], 'd', 'e']>>> mult[1][1]'b'>>> mult[2]'d'

The multi-dimensional list and access method are shown above. In multi-dimensional scenarios, the list is treated like a previous element.

List and str conversion

Str. split ()

This built-in function converts str to list. Str = "" is the separator.

Before looking at the example, you can see that the officer performs the following operations in interactive mode:

>>> Help (str. split)
Complete descriptions of this built-in function are provided. Special emphasis: this is a very good learning method.

split(...)S.split([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

Whether or not you have understood the above paragraph, you can refer to the example. I still hope the viewer can understand the above content.

>>> Line = "Hello. I am qiwsir. welcome you. ">>> line. split (". ") # use the English period as the separator to obtain the list ['hello', 'I am qiwsir', 'welcome you',''] >>> line. split (". ", 1) # This 1 represents: If maxsplit is given, at most maxsplit splits are done. ['hello', 'I am qiwsir. welcome you. '] >>> name = "Albert Ainstain" # space may also be used as the separator >>> name. split ("") ['Albert ', 'ainstain'] "[sep]". join (list)

Join can be called the inverse operation of split. for example:

>>> Name ['Albert ', 'ainstain'] >>> "". join (name) # concatenate the elements in the list, but there is no connector, indicating that the elements in the list are one by one adjacent to 'Albert tainstain '>>> ". ". join (name) # Use English periods as the separator 'Albert. ainstain '> "". join (name) # use space as the separator for connection 'Albert Ainstain'

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.