Python basic day03 [string (definition, input and output, common methods), list (definition, basic usage, addition, deletion, modification, nesting), tuple]

    

learning target:

  1. Be able to tell what is the use of the container type
  2. Able to name common Python containers
  3. Be able to tell the purpose of slicing syntax
  4. Be able to tell what the index in the container refers to
  5. Able to tell how to define a string
  6. Be able to tell the characteristics of the string container
  7. Be able to name at least 5 string method names and functions
  8. Ability to use slicing syntax to obtain substrings in the specified index range
  9. Can tell how to use while and for loops to traverse strings
  10. Able to tell how to define a list
  11. Can tell the difference between list container and string container
  12. Be able to name at least 5 list method names and functions
  13. Able to use slicing syntax to get the elements of the specified index range
  14. Can tell how to use while and for loops to traverse the elements in the list
  15. Able to tell how to define a list
  16. Be able to tell the difference between tuples and lists
  17. Can tell how to use while and for loops to traverse the elements in a tuple
  18. Able to tell what operations the tuple supports
  19. Able to tell how to define a dictionary
  20. Can tell the difference between a dictionary and a list
  21. Can tell how to use a for loop to traverse the keys, values, and key-value pairs in the list
  22. Can tell the characteristics of dictionary keys and values

table of Contents

Review and feedback

Today's content introduction

1. String

1.1 String definition

String * integer

1.2 String output and output

Output

enter

1.3 Subscripts of strings

1.4 Slicing of strings

1.5 How to find a string

find() & rfind()

index & rindex()

count()

1.6 Replacement method of string

1.7 Split() method of string cutting

1.8 String join()

1.9 Other methods of character strings [Common operations on character strings (extracurricular reading)]

<1>capitalize

<2>title

<3>startswith

<4>endswith

<5>lower

<6>upper

<7> bright

<8>rjust

<9>center

<10>lstrip

<11>rstrip

<12>strip

<13>rfind

<14>rindex

<15>partition

<16>rpartition

<17>splitlines

<18>isalpha

<19>isdigit

<20>isalnum

<21>isspace

2. List ["Add", "Delete", "Change", "Check"]

2.1 Definition and basic use of lists

2.2 Traverse

2.3 Add data to the list [add element ("add" append, extend, insert)]

2.4 Data query operation in the list [Find element ("check" in, not in, index, count)]

2.5 Delete operation in the list [modify element ("change"), delete element ("delete" del, pop, remove)]

2.6 List sorting and inversion [sort (sort, reverse)]

2.7 List nesting (two-dimensional list)

2.8 Case: Allocating Office

3. Tuple [Elements of tuple cannot be modified]

Container summary


Review and feedback

  

Today's content introduction

  Container: string, list, tuple, dictionary.

1. String

1.1 String definition

The variable a defined as follows stores a numeric value: a = 100.

The variable b defined as follows stores the value of string type: b = "hello itcast.cn" or b ='hello itcast.cn'.

The quoted content is the string.

  1. If the string itself contains single quotes, you can use double quotes to define;
  2. If the string itself contains double quotes, it can be defined with single quotes;
  3. Or use triple quotation marks uniformly.

String * integer

In python, a string can be multiplied by an integer: string * num.

1.2 String output and output

Output

Input: input() function-the content of input() function is a string.

Output: print() function-%s, f-string.

f-strings provides a concise and readable way to include Python expressions in strings. f-strings is prefixed with the letter'f' or'F', and the format string uses a pair of single quotes, double quotes, triple single quotes, and triple double quotes.

  

enter

When learning input(), it can be used to obtain data from the keyboard, and then save it to the specified variable;

Note: The data obtained by input is saved as a string, even if the input is a number, it is also saved as a string.

1.3 Subscripts of strings

The use of "subscripts" in strings: lists and tuples support subscript indexing. Strings are actually arrays of characters, so subscript indexing is also supported. If you want to take out some characters, you can use 下标the method (note that the subscript in python starts from 0).

1.4 Slicing of strings

Slicing refers to the operation of intercepting a part of the operation object. Strings, lists, and tuples all support slicing operations.

The slicing syntax: [start:end:step]

Note: The selected interval starts from the "start" bit and ends at the bit before the "end" bit (not including the end bit itself), and the step length indicates the selection interval.

Let's take string as an example to explain. If you take out a part, you can use in square brackets []:

  

Common operations of slicing:

  • my_str[:]: Get the same string as the original.
  • my_str[::-1]: The inverse of the string.

  

1.5 How to find a string

  1. find: Check if str is contained in mystr, if it is the starting index value, otherwise return -1.
  2. index: Same as find(), except that if str is not in mystr, an exception will be reported.
  3. count: Returns the number of times str appears in mystr between start and end.
  4. replace: Replace str1 in mystr with str2. If count is specified, the replacement will not exceed count times.
  5. split: slice mystr with str as the separator. If maxsplit has a specified value, only maxsplit+1 substrings will be separated.
  6. join: Insert mystr between each element in str to construct a new string.

find() & rfind()

index & rindex()

count()

1.6 Replacement method of string

  

1.7 Split() method of string cutting

  

1.8 String join()

1.9 Other methods of character strings [Common operations on character strings (extracurricular reading)]

<1>capitalize

Capitalize the first character of the string

mystr.capitalize()

<2>title

Capitalize the first letter of each word in the string

>>> a = "hello itcast"
>>> a.title()
'Hello Itcast'

<3>startswith

Check if the string starts with hello, if yes, return True, otherwise return False

mystr.startswith(hello)

<4>endswith

Check whether the string ends with obj, and return True if it is, otherwise return False.

mystr.endswith(obj)

<5>lower

Convert all uppercase characters in mystr to lowercase

mystr.lower()        

<6>upper

Convert lowercase letters in mystr to uppercase

mystr.upper()

<7> bright

Return a new string with the original string aligned to the left and padded with spaces to the length width

mystr.ljust(width)

<8>rjust

Return a new string with the original string right-aligned and padded with spaces to the length width

mystr.rjust(width)

<9>center

Return a new string with the original string centered and filled with spaces to the length width

mystr.center(width)   

<10>lstrip

Delete the blank character on the left of mystr

mystr.lstrip()

<11>rstrip

Delete the blank characters at the end of the mystr string

mystr.rstrip()

<12>strip

Remove the blank characters at both ends of the mystr string

>>> a = "\n\t itcast \t\n"
>>> a.strip()
'itcast'

<13>rfind

It is similar to the find() function, but searches from the right.

mystr.rfind(str, start=0,end=len(mystr) )

<14>rindex

Similar to index(), but starts from the right.

mystr.rindex( str, start=0,end=len(mystr))

<15>partition

Divide mystr into three parts by str, before str, after str and str

mystr.partition(str)

<16>rpartition

Similar to the partition() function, but starts from the right.

mystr.rpartition(str)

<17>splitlines

Separate by line, return a list containing each line as an element

mystr.splitlines()  

<18>isalpha

If all characters of mystr are letters, return True, otherwise return False

mystr.isalpha()  

<19>isdigit

If mystr contains only numbers, it returns True, otherwise returns False.

mystr.isdigit()

<20>isalnum

Returns True if all characters of mystr are letters or numbers, otherwise it returns False

mystr.isalnum()  

<21>isspace

If mystr contains only spaces, it returns True, otherwise it returns False.

mystr.isspace()   

2. List ["Add", "Delete", "Change", "Check"]

2.1 Definition and basic use of lists

The type of variable A is a list: namesList = ['xiaoWang','xiaoZhang','xiaoHua'].

What is more powerful than the C language array is that the elements in the list can be of different types: testList = [1,'a'].

2.2 Traverse

In order to output each data in the list more efficiently, you can use a loop to complete.

  

2.3 Add data to the list [add element ("add" append, extend, insert)]

The data stored in the list can be modified, such as "add", "delete", "change", and "check".

  1. append: You can add elements to the list through append.
  2. extend: Through extend, you can add elements from another set to the list one by one.
  3. insert: insert(index, object) Insert the element object before the specified position index.

2.4 Data query operation in the list [Find element ("check" in, not in, index, count)]

The so-called search is to see if the specified element exists. The common method of searching in python is:

  • in (exists), if it exists then the result is true, otherwise it is false.
  • not in (not in), if it does not exist, the result is true, otherwise it is false.

As long as the in method can be used, then not in is also used in the same way, except that not in judges that it does not exist.

Index and count are used in the same way as strings.

 

  

2.5 Delete operation in the list [modify element ("change"), delete element ("delete" del, pop, remove)]

When you modify an element, you must use the subscript to determine which element you want to modify before you can modify it.

Common ways to delete list elements are:

  • del: delete based on subscript
  • pop: delete the last element
  • remove: delete according to the value of the element

After an element in the list is deleted, subsequent elements will automatically move forward.

2.6 List sorting and inversion [sort (sort, reverse)]

The sort method is to rearrange the list in a specific order, the default is from small to large, the parameter reverse=True can be changed to reverse order, from large to small.

The reverse method is to reverse the list.

  

2.7 List nesting (two-dimensional list)

Similar to the nesting of while loops, lists also support nesting. An element in a list is a list, then this is the nesting of lists.

2.8 Case: Allocating Office

A school has 3 offices. Now there are 8 teachers waiting for the assignment of work positions. Please write the program to complete the random assignment.

  

3. Tuple [ Elements of tuple cannot be modified ]

tuple    English phonetic symbol: [ˈtjuːp(ə)l] American phonetic symbol: [ˈtjup(ə)l]    n. tuple; array; multiple

Python tuples are similar to lists, except that the elements of tuples cannot be modified . Use parentheses for tuples and square brackets for lists.

It is not allowed to modify the data of tuples in python, including the elements that cannot be deleted.

Container summary

Many people's understanding is not true, but general understanding, understanding is very superficial, not deep and impenetrable, and has no power to the environment! Just like what Zen said: "Speaking is like enlightenment, and I am fascinated by the state."

Guess you like

Origin blog.csdn.net/weixin_44949135/article/details/113587899