Code farming technology -- six months of learning python stack [Day07]

Today's learning objectives:

  • Understand other built-in methods of using strings
  • Understand and use list built-in methods
  • Understand and supplement knowledge points

Today's learning content:

Brief content:

  • Other built-in methods for strings (remainder)
  • List built-in method
  • Supplementary knowledge points

Details:

Other built-in methods for strings (remainder)

Please refer to my last article for the previous part[ Blog]

  • 1. Remove the specified characters at the beginning and end of the string, and you can choose the direction

    Usage examples

    str1 = '**jason***'
    
    print(str1.strip('*'))  # Remove the specified characters on the left and right
    print(str1.lstrip('*'))  # Remove only the specified characters on the left
    print(str1.rstrip('*'))  # Remove only the specified characters on the right
    
    

    Operation results

  • 2. Case related operations

    Usage examples

    str2 = 'My nAme is tonY!'
    
    print(str2.lower())  # Change all English strings to lowercase
    print(str2.upper())  # Capitalize all English strings
    

    Operation results

    Extended supplement

    • Judge whether all English letters in the string are pure lowercase or pure uppercase
      Usage examples

      str2 = 'My nAme is tonY!'
      
      print(str2.islower())  # Judge whether all English letters in the string are pure lowercase, and the result is Boolean
      print(str2.isupper())  # Judge whether all English letters in the string are pure uppercase, and the result is Boolean
      

      Operation results

      What is the reason why as like as two peas, the old authentication code can not be ignored.

      ***************************
       code = 'JaSOn6'
       print('This is the picture verification code returned to the user:%s' % code)
       user_code = input('Please enter the verification code>>>:').strip()
       if code.lower() == user_code.lower():  # The verification code ignores case and only needs to be converted to uppercase or lowercase
           print('The verification code is correct')
       ***************************
      
  • 3. Judge whether the beginning or end of the string is the specified character

    Usage examples

    str3 = 'tony jam'
    
    # Startswitch() determines whether the string starts with the character specified in parentheses, and the result is Boolean True or False
    print(str3.startswith('t'))
    print(str3.startswith('j'))
    
    # Endswitch() determines whether the string ends with the character specified in parentheses. The result is a Boolean value of True or False
    print(str3.endswith('jam'))
    print(str3.endswith('tony'))
    
    

    Operation results

  • 4. Format output

      1.Method 1 placeholder:%s %d
    

    See before me for detailed usage [blog]

      Mode 2 format method>>>:Four usages
    
    usagegive an example
    Placeholder consistent {} placeholderprint('my name is {} my age is {}'.format('jason', 18))
    According to the index value, it can be used repeatedlyprint('my name is {0} {0} {0} my age is {0} {1}'.format('jason', 18))
    Take values according to the way of naming and namingprint('my name is {name} {name} my age is {age} {pwd}'.format(name='jason', age=18, pwd=123))
    Continue to use variables that have already appearedname = 'jason' age = 18 print(f'my name is {name} my age is {age} {name} {age}')

    Usage examples

    # Play 1: use the {} placeholder consistent with the placeholder
    print('my name is {} my age is {}'.format('jason', 18))
    
    # 2: you can use the index repeatedly
    print('my name is {0} {0} {0} my age is {0} {1}'.format('jason', 18))
    
    # Play 3: take values according to the way of naming names
    print('my name is {name} {name} my age is {age} {pwd}'.format(name='jason', age=18, pwd=123))
    
    # Play 4: directly use the variables that have already appeared
    name = 'jason'
    age = 18
    print(f'my name is {name} my age is {age} {name} {age}')
    
    

    Operation results

    python's official website said long ago that format was recommended for formatted output, and even said that% s would be cut off

  • 5. Splice string

    modegive an example
    S1 + S2 (if the string is large, the plus sign is inefficient)$1600
    s1 * 10() repetition times$12
    'spliced characters' Join (spliced string)$1

    Usage examples

    s1 = 'March doesn't work hard, April becomes garbage'
    s2 = 'A young man who does not work hard is a young man'
    s3 = '2'
    print(s1 + s2)
    print(s3 * 10)
    print('|'.join(s1))
    print('$'.join(['jason', 'kevin', 'justin', 'tony']))
    

    Operation results

    The join method is equivalent to a for loop for the elements in parentheses, so the elements of the join must be strings, otherwise an error will be reported

  • 6. Replace the character specified in the string

    Usage examples

    str7 = 'my name is tony, my age is 18!'  # Change tony's age from 18 to 73
    str7 = str7.replace('18', '73')  # Syntax: replace('old content ',' new content ')
    print(str7)
    # You can specify the number of modifications
    str7 = 'my name is tony, my age is 18!'
    str7 = str7.replace('my', 'MY', 1)  # Change only one my to my
    print(str7)
    

    Operation results

  • 7. Judge whether the string is a pure number

    Usage examples

    # Judge whether the string is composed of pure numbers, and the return result is True or False
    str8 = '5201314'
    print(str8.isdigit())
    
    str8 = '123g123'
    print(str8.isdigit())
    
    

    Operation results

The following methods are used less frequently and only for understanding

  • 1. Find the index value corresponding to the specified character

    modedifference
    The string to find find('found character') # from left to right, find one and endprint(s1.find('k ', 1, 9)) # - 1 means not found
    The string to find index('characters found ')print(s1.index('k ', 1, 9)) # can't be found. Direct error reporting is not recommended

    Usage examples

    s1 = 'jason justin kevin tony'
    print(s1.find('s'))
    print(s1.find('k', 1, 9))
    print(s1.index('s'))
    print(s1.index('k', 1, 9))  
    
    

    Operation results

  • 2. Change the position of the text

    grammargive an example
    Changed string Center (number of characters added, characters added)name = 'tony' print(name.center(30, '-'))
    Changed string Ljust (number of characters added, characters added)name = 'tony' print(name.ljust(30, '*'))
    Changed string Rjust (number of characters added, characters added)name = 'tony' print(name.rjust(30, '$'))
    Changed string Zfill (number of characters added, characters added)name = 'tony' print(name.zfill(50))

    Usage examples

    name = 'tony'
    print(name.center(30, '-')) 
    print(name.ljust(30, '*'))
    print(name.rjust(30, '$'))
    print(name.zfill(50))
    

    Operation results

  • 3. Special symbols: the combination of slash and some English letters will produce special meanings

    stylemeaning
    \nRepresents a newline character that changes to the beginning of the next line.
    \aSpecial symbols, placeholders
    \tRepresents a tab. Move the cursor to the next tab, just like using the tab key in a document

    Usage examples

    print('ja\tson\nke\avin')
    '''
    result
    ja	son
    kevin
    '''
    
  • 4 captalize: initial capital
    Usage examples

     message = 'hello everyone nice to meet you!'
     message.capitalize()
    # Hello everyone nice to meet you!
    

    Operation results

  • 5.swapcase: case reversal
    Usage examples

     message1 = 'Hi girl, I want make friends with you!'
     message1.swapcase()
    # hI GIRL, i WANT MAKE FRIENDS WITH YOU!
    

    Operation results

  • 6 title: capitalize the first letter of each word
    Usage examples

     msg = 'dear my friend i miss you very much'
     msg.title()
    # Dear My Friend I Miss You Very Much
    

List built-in method

  • 1. Type conversion

    Usage examples

    print(list(11))  # no way
    print(list(11.11))  # no way
    print(list('jason'))  # ['j', 'a', 's', 'o', 'n']
    print(list({'name': 'jason', 'pwd': 123}))  # ['name', 'pwd']
    print(list((11,22,33,44,55)))  # [11, 22, 33, 44, 55]
    print(list({1, 2, 3, 4, 5}))  # [1, 2, 3, 4, 5]
    print(list(True))  # no way
    

    list can convert data types that support for loops

  • 2. Index value

    Usage examples

    name_list = ['jason', 'kevin', 'tony', 'tom', 'jerry']
    print(name_list[0])  # jason
    print(name_list[-1])  # jerry
    
  • 3. Slicing operation

    Usage examples

     name_list = ['jason', 'kevin', 'tony', 'tom', 'jerry']
     print(name_list[1:4])  # ['kevin', 'tony', 'tom']
     print(name_list[-4:-1])  # ['kevin', 'tony', 'tom']
    
  • 4. Step size

    Usage examples

    name_list = ['jason', 'kevin', 'tony', 'tom', 'jerry']
    print(name_list[0:4:1])  # ['jason', 'kevin', 'tony', 'tom']
    print(name_list[0:4:2])  # ['jason', 'tony']
    print(name_list[-1:-4:-1])  # ['jerry', 'tom', 'tony']
    
  • 5. Count the number of elements in the list

    Usage examples

    name_list = ['jason', 'kevin', 'tony', 'tom', 'jerry']
    print(len(name_list))  # 5
    
  • 6. The minimum judgment unit of member operation is the element, not a single character in the element

    Usage examples

    name_list = ['jason', 'kevin', 'tony', 'tom', 'jerry']
    print('j' in name_list)  # False
    print('jason' in name_list)  # True
    
  • 7. How to add elements to the list

    modeexample
    Added list append('element ') # append' single 'element at the endname_list.append('xiao Li ')
    Added list Insert (position, element) # inserts a 'single' element at a specified positionname_list.insert(0, 123)
    List 1 Extend (list 2) # merge listname_list.extend([11, 22, 33, 44, 55])

    Usage examples

    name_list = ['jason', 'kevin', 'tony', 'tom', 'jerry']
    # Append 'single' element to the tail
    name_list.append('petty thief')
    print(name_list)
    name_list.append([11, 22, 33, 44])
    print(name_list)
    # Insert a 'single' element at the specified location
    name_list.insert(0, 123)
    name_list.insert(2, 'Can you join the team')
    name_list.insert(1, [11, 22, 33])
    print(name_list)
    # Merge list
    name_list.extend([11, 22, 33, 44, 55])
    print(name_list)
    

    Operation results

    extend can actually be regarded as a for loop + append

  • 8. Delete element

    modegrammar
    General deletion methoddel list [location]
    Delete in place, directly delete an elementList Remove (element to be deleted)
    Delayed deletionList Pop (specify index value) deletes the tail by default

    Usage examples

    name_list = ['jason', 'kevin', 'tony', 'tom', 'jerry']
    # General deletion method
    del name_list[0]
    print(name_list)
    # Delete in place
    print(name_list.remove('jerry'))
    print(name_list)
    # Delayed deletion
    print(name_list.pop())
    print(name_list)
    
    

    Operation results

  • 9. Modify list elements

    Usage examples

    name_list = ['jason', 'kevin', 'tony', 'jerry']
    print(id(name_list[0]))
    name_list[0] = 'tom'
    print(id(name_list[0]))
    print(name_list)
    

    Operation results

  • 10. Sorting

    Usage examples

     ss = [44, 77, 99, 11, 22, 33, 88, 66]
     ss.sort()  # The default is ascending
     print(ss)  # [11, 22, 33, 44, 66, 77, 88, 99]
     ss.sort(reverse=True)  # You can modify the tail descending order
     print(ss)  # [99, 88, 77, 66, 44, 33, 22, 11]
    

    Operation results

  • 11. Flip

    Usage examples

    ss = [44, 77, 99, 11, 22, 33, 88, 66]
    ss.reverse()  # Back and forth
    print(ss)
    

    Operation results

  • 12. Comparison operation

    Usage examples

    s1 = [11, 22, 33]
    s2 = [1, 2, 3, 4, 5, 6, 7, 8]
    print(s1 > s2)  # True
    s1 = ['A', 'B', 'C']  # A>>>65
    s2 = ['a']  # a>>>97
    print(s1 > s2)  # False
    

    Operation results

    When comparing lists, they actually compare the elements in the corresponding index position

  • 13. Count the number of occurrences of an element in the list

    Usage examples

    l1 = [11, 22, 22, 11, 22, 11, 22, 33, 44, 55, 44, 33]
    print(l1.count(11))  # Counts the number of occurrences of element 11
    

    Operation results

  • 14. Clear the list
    Usage examples
    l1 = [11, 22, 22, 11, 22, 11, 22, 33, 44, 55, 44, 33]
    l1.clear()  # clear list 
    print(l1)
    
    Operation results

Variable type and immutable type

When you first learn python, you may have a lot of doubts, especially the so-called "variable data type" and "immutable data type". Python is different from C/C + +. Its variable use has its own characteristics. First, we need to know which data types are mutable and which are immutable in Python. Variable data types: list and dictionary dict; Immutable data types: integer int, floating point float, string string and tuple.

  • Immutable data type analysis
>>> x = 1
>>> id(x)
31106520
>>> y = 1
>>> id(y)
31106520
>>> x = 2
>>> id(x)
31106508
>>> y = 2
>>> id(y)
31106508
>>> z = y
>>> id(z)
31106508


>>> x += 2
>>> id(x)
31106484 

The above procedures are all operations on the int type in the immutable data type. id() looks at the address value of the current variable. Let's first look at the results of the two operations x = 1 and y = 1. From the above output, we can see that the address values of X and y are the same at this time, that is, X and Y actually refer to the same object, i.e. 1, that is, only one address is occupied for 1 in memory, and no matter how few references point to it, there is only one address value, Just a reference count will record how many references point to this address. When we assign x = 2, we find that the address value of X has changed. Although it is still the reference of X, its address value has changed. The following y = 2 and z = y make x, y and Z refer to the same object, i.e. 2, so the address values are the same. When x and y are assigned 2, the object 1 has no reference to it, so the memory occupied by the object 1, that is, the address 31106520, will be "garbage collected", that is, the object 1 no longer exists in memory. Finally, x adds 2, so a new object 4 is created. X references the new object instead of 2.

  • Variable data type analysis
>>> a = [1, 2, 3]
>>> id(a)
41568816
>>> a = [1, 2, 3]
>>> id(a)
41575088
>>> a.append(4)
>>> id(a)
41575088
>>> a += [2]
>>> id(a)
41575088
>>> a
[1, 2, 3, 4, 2]

It can be seen from the above program that when a = [1, 2, 3] is operated twice, the address values referenced by a are different, that is, two different objects are created, which is obviously different from the immutable data type. Therefore, for the variable data type, objects with the same value are different objects, that is, multiple objects with the same value are saved in memory, Address values are different. Next, let's look at the following operations. We add a.append(4) and a += [2] to the list. We find that these two operations make the object value referenced by a become the final result above, but the address referenced by a is still 41575088, that is, the operation on a will not change the address value referenced by a, but expand a new address after the address, The value stored in the address is changed, so the variable data type means that when a variable is operated, its value is variable. The change of value will not cause the new object, that is, the address will not change, but the content in the address has changed or the address has been expanded.

summary

Variable and immutable types:
    Variable type     list
        The value changes, the memory address remains unchanged, and what is modified is itself
    Immutable type string
        When the value changes the memory address, the modification process must produce a new value

Queue and stack

queue
	fifo
    	eg:Supermarket queuing checkout conforms to the characteristics of queuing
 stack
	In and out
    	eg:Folding clothes conforms to the characteristics of the stack
# Use lists to simulate the characteristics of queues and stacks

# queue
 new_list = []
# advanced
 new_list.append(111)
 new_list.append(222)
 new_list.append(333)
# First out
 for i in new_list:
     print(i)
 print(new_list.pop(0))
 print(new_list.pop(0))
 print(new_list.pop(0))

# stack
new_list = []
# advanced
new_list.append(111)
new_list.append(222)
new_list.append(333)
# Back out
print(new_list.pop())
print(new_list.pop())
print(new_list.pop())

Queue running results

Stack run results

Today's study time:

Here you can count the planned learning time

1. 8:30-12:30 am
2. 2:30 ~ 5:30 pm
3. 6:30 ~ 9:30 pm

Today's learning output:

Here is the total number of learning plans

  • 1. Technical notes 1 time
  • 2. CSDN technology blog 1
  • 3. Daily recording
  • 4. Homework after class
    Write user login mode
    2. Use the list to write a user registration and login program
    Tip: loop
    Requirements: it can succeed once, without considering user conflict and other situations
    3. Count is not used to count the number of occurrences of the specified element in the list
    data = 'jason|123'
is_tag = True
count = 1
source_data = ['jason|123', 'tony|123', 'kevin|321', 'jerry|222']
while is_tag:
    # Prompt after three errors and ask whether to re register
    if count == 4:
        ask = input('You have tried three times. Do you want to continue(y/n) Or do you need to re register an account(z)>>>:')
        if ask == 'y':
            count = 1
        # Implementation of registration function
        elif ask == 'z':
            username01 = input('Please enter your user name>>>:').strip()
            # Judge whether the user input is empty
            if len(username01) == 0:
                print('User name cannot be empty')
                continue
            password01 = input('Please enter your password>>>:').strip()
            # Judge whether the user input is empty
            if len(password01) == 0:
                print('Password cannot be empty')
                continue
            print(f'Your user name:{username01},password:{password01}')
            # Format the user name and password entered by the user and store them in the list 'source'_ data’
            count02 = username01 + '|' + password01
            source_data.append(count02)
            count = 1
        else:
            print('Bye!!')
            break
    # Prompt the user for input and ask if registration is required
    username = input('Please enter your user name[Do you need to register user name and password(y)]>>>').strip()
    # Judge whether the user input is empty
    if len(username) == 0:
        print('User name cannot be empty')
        continue
    # Implementation of registration function
    if username == 'y':
        username = input('Please enter your user name>>>:').strip()
        # Judge whether the user input is empty
        if len(username) == 0:
            print('User name cannot be empty')
            continue
        password = input('Please enter your password>>>:').strip()
        # Judge whether the user input is empty
        if len(password) == 0:
            print('Password cannot be empty')
            continue
        # Format the user name and password entered by the user and store them in the list 'source'_ data’
        print(f'Your user name:{username},password:{password}')
        count02 = username + '|' + password
        source_data.append(count02)
        continue
    password = input('Please enter your password>>>:').strip()
    # Judge whether the user input is empty
    if len(password) == 0:
        print('Password cannot be empty')
        continue
    # Format the user name and password entered by the user, and judge whether the user name and password are correct by member operation
    count01 = username + '|' + password
    if count01 in source_data:
        print('Login successful')
        # Realization of user instruction function
        while is_tag:
            cmd = input('Enter your instructions>>>:').strip()
            print(f'Executing the command you entered({cmd})....')
            if cmd == 'byb':
                print('See you next time!')
                is_tag = False
    else:
        print('Wrong user name or password!')
        count += 1

Keywords: Python

Added by Drezard on Wed, 09 Mar 2022 15:08:34 +0200