day10 string

day10 string

1. Correlation functions: len, str, eval
  • str (data) - converts the specified data into a string (any type of data can be converted into characters; when converting, it is directly quoted outside the printed value)

  • eval (string) - evaluates the result of a string expression

2. String correlation method
  • join

    • character string. Join - concatenates the elements in the sequence into a string using the specified string (the elements in the sequence must be strings)

      list1 = ['n', 'g', 'b']
      num1 = '+'.join(list1)
      print(num1)
      
    • Exercise: use # to connect all the elements in the list into a string

      num2 = [100, 12.8, True, 'abc']
      num1 = '#'.join([str(x) for x in num2])
      print(num1)
      
  • split

    • String 1 Split (string 2) - use all string 2 in string 1 as the cutting point to cut the string
      • Note 1: if the cutting point is at the beginning or end, an empty string will appear after cutting
      • Note 2: if cutting points appear continuously, empty strings will appear continuously after cutting
    • String 1 Split (string 2, N) - use the first N string 2 in string 1 as the cutting point to cut the string
    • String 1 Rsplit (string 2, N) - cut the string by taking N string 2 from right to front in string 1 as the cutting point
  • Replace - replace

    • String 1 Replace (string 2, string 3) - replaces all string 2 in string 1 with string 3

    • String 1 Replace (string 2, string 3, N) - replaces the first N string 2 in string 1 with string 3

      Practice will str1 The last two in'you'replace with'me'
      str1 = 'how are you? i am fine, thank you! and you?'
      num1 = 'me'.join(str1.rsplit('you', 2))
      print(num1)
      
  • Replace character

    • Str.maketrans (string 1, string 2) - create a one-to-one correspondence table between all characters in string 1 and all characters in string 2

    • character string. Translate (character correspondence table) - replace the string according to the relationship of the character correspondence table

      num1 = ' 1123jigugg456 '
      # Replace all '1' with 'one', replace all 'g' with 'g' - > 'one by one 23jiGuGG456'
      num2 = num1.maketrans('1g', 'one G')
      num3 = num1.translate(num2)
      print(num3)
      
  • Delete whitespace at both ends of a string

    • character string. strip() - delete whitespace at both ends of the string
    • character string. rstrip() - delete the blank space at the right end of the string
    • character string. lstrip() - delete the blank space at the left end of the string
  • Count - count

    • String 1 Count (string 2) - counts the number of string 2 in string 1
3. String formatting
  • character string
    • Format string: string containing format placeholder% (data 1, data 2, data 3,...)
    • Note: the data in () must correspond to the placeholder in the character one by one
  • Format placeholder
    • %s - string placeholder, which can correspond to any type of data
    • %d - integer placeholder, which can correspond to any number
    • %f - floating point placeholder, which can correspond to any number (six decimal places after the decimal point are reserved by default)
    • %. Nf - floating point placeholder, which can correspond to any number. N determines the number of decimal places to be reserved
4,f - string
  • f '{expression}' - splice the value of the expression in {} into the string as a string

    a = 190
    num1 = f'a:{a}, b:{100 + 100},c:{"abc"[-1]}'
    print(num1)
    
  • f '{data expression: parameter}'

  • f '{expression:. Nf}' - keep N decimal places

  • Amount value display plus comma

    • Comma only: f '{expression:}'

      num1 = 100000
      nums = f'amount of money:{num1:,}'
      print(nums)
      
    • Add a comma and keep two decimal places

      num1 = 100000
      num2 = f'amount of money{num1:,.2f}'
      print(num2)
      
  • Display percentage

    • f '{expression:. N%}' - N controls the number of decimal places

      x = 0.43  # 34%
      num3 = f'{x:.0%}'
      print(num3)
      
  • Control length

    • f '{expression: x > y}' - the expression is the character of the given filling coordinate, X indicates the filling content, and Y controls the filling length. If it is greater than the symbol, it is filled before the expression, and if it is less than the symbol, it is filled after the expression

      num1 = 1
      num2 = f'This is a number{num1:3>5}'
      print(num2)  # This is a number 33331
      

Homework practice

  1. Write a program to exchange the key and value of the specified dictionary.

      for example:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}  
    
    dict1 = {'a': 1, 'b': 2, 'c': 3}
    num1 = {dict1[x]: x for x in dict1}
    print(num1)
    
  2. Write a program to extract all the letters in the specified string, and then splice them together to produce a new string

       for example: afferent'12a&bc12d-+'   -->  'abcd'  
    
    num1 = '12a&bc12d-+'
    num2 = ''
    for x in num1:
        if 'a' <= x <= 'z':
            num2 += x
    print(num2)
    
  3. Write your own capitalize function, which can turn the first letter of the specified string into uppercase letters

      for example: 'abc' -> 'Abc'   '12asd'  --> '12asd'
    
    num1 = str(input('Please enter a string:'))
    num2 = ''
    if 'a' <= num1[0] <= 'z':
        num2 += chr(ord(num1[0])-32)
        for x in range(1, len(num1)):
            num2 += num1[x]
    else:
        print(num1)
    print(num2)
    
  4. The writer realizes the function of endswitch to judge whether a string has ended with the specified string

       for example: String 1:'abc231ab' String 2:'ab' The result of the function is: True
            String 1:'abc231ab' String 2:'ab1' The result of the function is: False
    
    num1 = 'abc231ab'
    num2 = 'ab'
    nums = ''
    for x in range(len(num1)-len(num2), len(num1)):
        nums += num1[x]
        if nums == num2:
            print('True')
            break
    else:
        print('False')
    
  5. Write a program to realize the function of isdigit and judge whether a string is a pure digital string

       for example: '1234921'  result: True
             '23 function'   result: False
             'a2390'    result: False
    
    num1 = str(input('Please enter a string:'))
    for x in num1:
        if not('0' <= x <= '9'):
            print('False')
            break
    else:
        print('True')
    
  6. Write a program to realize the function of upper and turn all lowercase letters in a string into uppercase letters

        for example: 'abH23 good rp1'   result: 'ABH23 good RP1'   
    
  7. The writer gets the maximum value of the element in the specified sequence. If the sequence is a dictionary, take the maximum value of the dictionary value

      for example: sequence:[-7, -12, -1, -9]    result: -1   
           sequence:'abcdpzasdz'    result: 'z'  
           sequence:{'Xiao Ming':90, 'Zhang San': 76, 'Monkey D Luffy':30, 'floret': 98}   result: 98
    
    num1 = 'abH23 good rp1'
    num2 = ''
    for x in num1:
        if 'a' <= x <= 'z':
            num2 += chr(ord(x)-32)
        else:
            num2 += x
    print(num2)
    
  8. The writer implements the function of replace function to convert the old string specified in the specified string into the specified new string

        for example: Original string: 'how are you? and you?'   Old string: 'you'  New string:'me'  result: 'how are me? and me?'
    
    str1='how are you? and you?'
    str2='you'
    str3='me'
    str4=''
    x=0
    length=len(str2)
    while x < len(str1):
        if str1[x:x+length]==str2:
            str4+=str3
            x+=length
        else:
            str4+=str1[x]
            x+=1
    print(str4)
    
  9. Write a program to realize the function of split, and cut the string by taking the stator string in the string as the cutting point

    For example: original string: 'how are you? and you?'   Cutting point: 'you'  result: ['how are ', '? and ', '?']
    
    str1 = 'how are you? and you?'
    str2 = 'you'
    list1 = []
    str3 = ''
    length = len(str2)
    x = 0
    while x < len(str1):
        if str1[x:x+length] == str2:
            list1.append(str3)
            str3 = ''
            x+= length
        else:
            str3 += str1[x]
            x+=1
    list1.append(str3)
    print(list1)
    
  10. Summarize four containers with mind map: list, dictionary, tuple and set

Keywords: Python

Added by dewed on Sun, 27 Feb 2022 18:19:54 +0200