The third piece of Python basics

Source: Internet
Author: User

I. Coding
1. The earliest computer encoding is ASCII. Created by Americans. Contains the English alphabet (uppercase letters, lowercase letters). Special characters such as numbers, punctuation, etc. [email protected]#$%
128 code point 2**7 on this basis added a 2**8
8 bits. 1 bytes (byte)
2. GBK GB code 16 bit. 2 bytes (double-byte characters)
3. Unicode universal Code 32 bits, 4 bytes
4. Utf-8: English 8 bit 1 bytes
European Writing 16bit 2 bytes
Chinese 24bit 3 bytes

8bit = 1 byte
1024x768 byte = > 1kb
1024x768 = 1MB
1024MB = 1GB
1024GB = > 1TB
Two. Python Basic data type

    1. an int ==> integer. To come in? Mathematical operations
    2. STR ==> string, can save a small amount of data to keep up? corresponding operation
    3. Bool==> judgment True, false
    4. List==> storage volume data.? [] table?
    5. Tuple=> tuple, can not send? change? () Table?
    6. Dict==> dictionary, save key value pair, sample can save? Volume data
    7. Set==> collection, save the volume data. Can not be repeated. In fact, it is not the dict to save value

1). Integer (int)
All integers in Python3 are of type int. But in Python2 if the amount of data is compared? Will make a long type.
There is no long type in Python3
An integer that can be manipulated:
Bit_length (). Calculates the length of the binary code that an integer occupies in memory

Three. Boolean value (BOOL)
The value is only true, False. BOOL value does not operate.
Conversion issues:
str = = int int (str)
int = str str (int)
int = bool bool (int). 0 is false, not 0 is true
Bool=>int Int (BOOL) True is 1, false is 0
str = = bool bool (str) empty string is false, not NULL is true
bool = str STR (BOOL) converts the bool value to the corresponding "value"

Four. String (str)
String the characters together. In Python? ', ', ', ', ' "" is what is called a string.

4.1 Slices and indexes
1. Index. The index is the subscript. Remember, the subscript starts at 0

2. Slices, we can make the subscript to intercept the contents of a part of the string
Syntax: Str[start:end]
Rule: Gu Tou disregard butt, starting from start intercept. Intercept to the end position. But does not include end

Step: If it is an integer, it is taken from left to right. If it is a negative number. It is taken from right to left. Default is 1
Slice syntax:
Str[start:end:step]
Start: Start position
End: Ending position
Step: Steps?

s = "Alex and Wusir often work together" S1 = s[5:10]print (s1) s2 = s[0:4] + s[5:10]print (s2) s3 = s[5:]  # Default to end print (s3) S4 = S[:10] # start over Print (s4) S5 = s[:]   # cut it out from start to finish print (s5) s6 = S[-2:] # from 2 to end the default left-to-  right cut print (S6) Step syntax: s[start Position: End Position: Step]s = "I'm Lionel Messi, I'm panicking." S1 = S[1:5:2]   # starting from 1, to 5 end, every 2 fetch 1 print (s1) s2 = s[::3]print (s2) s3 = s[6:2:-1]   #-means reverse. Every two x print (s3) s = "This punctuation It hurts "# S1 = s[7::-2]# print (s1) s2 = s[-1:-6:-2]print (s2)

4.2 Related operations of strings?
Remember that a string is an immutable object, so any action will have no effect on the original string.

1.?? Write and Spin

s = "Alex and Wusir and taibai" S1 = S.capitalize ()  # Initial capital print (s)    # original string invariant print (S1) s = "Alex is not a good man." Print (S.upper ()) print (S.lower ()) when the program needs to determine the case-insensitive. Must be able to use the while True:    content = input ("Please spray:")    if content.upper () = = ' Q ': Break    Print ("You sprayed:", content) s = " Taibai Henbai feicahngbai "Print (S.swapcase ()) # case Conversion s =" Al Twist Vine ex and Wu Sir Se "Print (s.title ())

2. Che cut away

s = "Twist vine" Print (S.center (9, "*")) Username = input ("username:"). Strip ()    # Remove the space. Password = input ("Password:"). Strip ()     # Remove the space if username = = ' Alex ' and password = = ' 123 ':    print ("login Successful") Else:    print ("Login Failed") s = "******* ah a oh hehe ************* Print (S.strip ("*"))   # Strip The contents of the left and right sides are removed. The middle of whatever s = "Alex Wusir Alex sb Taibai" S1 = S.replace ("Alex", "Xiao Xue") # Original String invariant p Rint (S1) # Remove all spaces from the above string s2 = S.replace ("", "") Print (s2) s3 = S.replace ("Alex", "SB", 2) print (s3) s = "Alex_wuse_taibai_buba I "LST = S.split (" _taibai_ ")    # knives are  the list of things that are finished. The list is loaded with string print (LST)

3. Formatted output

s = "My name is {}, I am {} years old, I like {}". Format ("Sylar", 18, "Jay Chou's Wife") print (s) can specify position s = "I'm {1}, I'm {0} years old, I like {2}". Format ("Sylar", 18, "Week Jay's Wife ") print (s) s =" My Name {name}, I am {age} year old, I like {mingxing} ". Format (name=" Sylar ", mingxing=" Wang Feng Wife ", age=18) print (s) You can use whichever you like.

4. Find

s = "Wang Feng's wife does not love Wang Feng" print (S.startswith ("Wang Feng")   # Determines whether the string starts with XXX print (S.endswith ("Princess"))     # To determine whether the string ends with XXX print ( S.count ("International Chapter")   # Calculates the number of times that XXX appears in the string print (S.find ("Wang Feng", 3))    # Calculates the position of the XXX string in the original string if it does not appear to return -1print ("International Chapter ")    # Content in Index if it does not exist. Direct error

5. Conditional judgment

s = "abc123" Print (S.isdigit ()) # Determines whether a string consists of a  number print (S.isalpha ()) # Whether it consists of  letters print (S.isalnum ())  # Whether it consists of letters and numbers s = "21.36 million" Print (S.isnumeric ())    # number

6. Calculate the degree of the string

s = "Are you drinking today?" I = Len (s)  #  print () input () Len () Python's built-in function print (i) i = s.__len__ () # can also be used to find the length Len () function is actually executed when it is executed. Print (i)

Note: Len () is a python built-in function. So the access to the style is not like. You remember Len () and print ()? The

7. Iteration
We can make the? For loop to facilitate (get) every character in a string
Grammar:
The for variable in can iterate over the object:
Pass
An iterative object: Can you? A value-taking object

#把字符串从头到尾进行遍历s = "Miss Snow." Print (len (s))   # length is: 8 index to 7#1. Use a while loop to traverse count = 0while Count < Len (s):    print ( S[count])    count = Count + 1#2. Use for loop to traverse string # Advantages: Simple # Disadvantage: No index for C in S: # give each character in s to the front C loop    print (c) #语法:    #for Bi Anliang  in  Iteration object:        #循环体

After-school assignments:

A. Variable name = "AleX leNb" do the following:
Name = "AleX leNb" #1) remove the space on both sides of the value of the name variable and output processing result s = Name.strip () print (s) #2) Remove the "Al" to the left of the name variable and output the processing result s = Name.lstrip (" Al ") print (s) #3) remove the name variable right of" Nb "and output processing result s = Name.rstrip (" NB ") print (s) #4) remove the name variable at the beginning of" a "with the last" B "and output the processing result s = Name.lstrip (  "a"). Rstrip ("B") print (s) #5) determine if the name variable begins with "Al" and outputs the result s = Name.startswith ("Al") print (s) #6) to determine if the name variable ends with "Nb" and outputs the result s = Name.endswith ("Nb") print (s) #7) replaces all "L" in the value corresponding to the name variable with "P" and outputs the result s = Name.replace ("L", "P") print (s) #8) corresponding to the name variable The value of the first "L" is replaced with "P", and the output result s = Name.replace ("L", "P", 1) print (s) #9) the value corresponding to the name variable is divided according to all "L", and output results. s = Name.split ("L") print (s) #10) splits the value corresponding to the name variable according to the "L" and outputs the result. s = Name.split ("L", 1) print (s) #11) writes the value corresponding to the name variable and outputs s = Name.upper () print (s) #12) writes the value corresponding to the name variable and outputs the result s = name. Lower () print (s) #13) the value corresponding to the name variable? A "write and output the result s = Name.replace (" A "," a ") print (s) #14) determine the value word corresponding to the name variable?" L "appears at times and outputs the result s = Name.count (" L ") print (s) #15) If you determine the value of the name variable corresponding to the first four bits" L "appears, and the output result s = Name[0:3].count (" L ") print (s) #16) from the name Variables corresponding to theThe index of "n" is found in the value (if no error is found), and the output s = Name.index ("n") print (s) #17) find the index corresponding to "n" from the value corresponding to the name variable (return-1 if not found) output s = Name.find ("n" Print (s) #18) find the index of "x le" from the value corresponding to the name variable and output the result s = Name.find ("x le") print (s) #19) output the 2nd character of the value corresponding to the name variable? print (Name[2] ) #20) Output the first 3 characters of the value corresponding to the name variable? print (Name[0:3]) #21) output The last 2 characters of the value corresponding to the name variable? Print (name[-2:]) #22) Please output the value of the name variable Where is the "E" index located? s = Name.find ("E") print (s)
Two.. There is a string s = "123a4b5c"
s = "123a4b5c"    #1) through to s tangent? form a new string s1,s1 = "123" S1 = S.strip ("a4b5c") print (S1)    #2) by the S tangent? form a new string s2,s2 = "a4b" s2 = S.lstrip ("123"). Rstrip ("5c") print (s2)    #3) through the S-tangent? form a new string s3,s3 = "1345" s3 = S[0::2].strip ("") print (S3)    #4) Through the S-tangent? form string s4,s4 = "2ab" S4 = S[1:6:2].strip ("") print (S4)    #5) through to S tangent? form string s5,s5 = "C" s5 = S.strip ("123ab45") print (S5)    #6) through the S-tangent? form string s6,s6 = "Ba2" s6 = S[-3:-8:-2].strip ("") Print (S6)
Three. Make the. While and for loops print each element of the string s= "Asdfer", respectively.
#1. While loop printing s = "asdfer" Count = 0while count <= Len (s)-1: Print    (S[count])    count = Count +1#2.for loop print s = "as Dfer "For a in S:    print (a)
Four. s= "Asdfer" into the loop for the for loop, but each time the content is printed is "Asdfer".
s = "Asdfer" for a in S:  print (s)
Five. For loop to s= "ABCDEFG" into the loop, each time the content printed is each character plus SB, for example: ASB, BSB,CSB,... GSB.
s = "ABCDEFG" for a in S:    print (A + "SB")
Six. For loop to s= "321" into the loop, print the content in order: "Countdown 3 Seconds", "Countdown
2 Seconds "," Countdown 1 Seconds "," Go! " "。
s = "321" for a in S:    print ("Countdown%s Seconds"% (a)) Else:    print ("Go!")
Seven, to implement an integer addition calculator (two numbers added):
For example: content = input ("Please lose content:")?: 5+9 or 5+ 9 or 5 + 9, then enter
? split and forward calculation.
Content = input ("Please Lose contents:"). Strip () s = content.split ("+") s2 = Int (s[0]) +int (s[1]) print (s2)
Eight, upgrade: implementation of the integer addition calculator (multiple numbers added):
For example: content = input ("Please lose content:")?: 5+9+6 +12+ 13, then enter?
Partitioning and re-entering? calculation.
Content = input ("Please Lose contents:"). Strip () lis = Content.split ("+") A1 =len (LIS) count = 0sum = 0while Count < a1:    sum = sum + Int (Lis[count])    count = count + 1print (sum)
Nine, the calculation of the contents of the loss is an integer (in single digit units).
such as: content = input ("Please lose Content:") # such as Fhdal234slfh98769fjdla
Content = input ("Please Lose contents:"). Strip () Count = 0b = 0while count < len (content):    c = content[count]    if C.isdigit (): 
   b + = 1    count + = 1print ("Input with%s integer"% (b))
10. Write the code to complete the following requirements:
In the case of a sustainable loss (? While loop), the user is allowed to:
Lose? A, then show?? Road to go home, and then in the Let the door into the step to choose:
Are you choosing a bus or a step?
Select Bus, show 10 minutes home, and exit the entire program.
Select step, show 20 minutes home, and exit the entire program.
Lose? B, then show?? Road Home and quit the whole program.
Lose? C, then show a detour home, and then in the Let the door into the step to choose:
Would you prefer to play in a game hall or something?
Select the game hall, then show '? ' When you get home, Daddy is at home, and you're waiting for a stick. ' And let it
Lose again? A,b,c option.
Choose, then Show ' two? When you get home, Mom's ready to fight? ' and make it heavy
New loser? A,b,c option.
While True:    s = input ("Please enter one of the A,b,c:"). Upper ()    if s = = "A":        print ("Take the Road Home")        S1 = input ("Choose bus or Walk:")        if S1 = = "Walk":            print ("20 minutes Home") Break        if S1 = = "Bus":            print ("10 minutes Home") Break    if s = = "B": C12/>print ("Take the Path Home") Break    if s = = "C":        while True:            print ("Detour home")            s2 = input ("Choose to go to the arcade or go to the Internet Café:")            if S2 = = "Arcade":                print ("When you get home, Dad is at home, and he is waiting for you.") ")                break            if s2 = =" Internet café ":                print (" Two? When you get home, Mom is ready to fight? "). ") Break                
11. Write code: Calculate 1-2 + 3 ... + 99 The sum of all the numbers except 88?
Count = 1sum = 0while Count <:    if Count = =:        count + = 1        continue    if count% 2 = = 0:        sum = sum -Count    else:        sum = sum + count    count = count + 1print (sum)
Twelve. (upgrade question) to judge, whether the sentence is back? Back to: Just read and read the opposite. For example, Shanghai
Come on, come on. Sea (upgrade problem)
s = input ("Please enter a word") if s[::-1] = = S:    print ("Palindrome") Else:    print ("Not palindrome")
13. Lose?? A string that asks to be judged in this string?, write, write, number,
How many other characters are present and output
s = input ("Please enter a sentence") Upper_num = 0lower_num = 0num = 0other = 0for A in s:    if A.isupper ():        upper_num + 1    Eli F A.islower ():        lower_num + = 1    elif a.isdigit ():        num + = 1    Else: other        + = 1
Print ("There are%s in uppercase letters, primary letters have%s, numbers have%s, others have%s"% (Upper_num,lower_num,num,other))
14, the production of interesting template program requirements: Waiting for the user to lose the name, place, hobby, according to the name of the household
Words and hobbies into the arbitrary reality such as: love and amiable xxx, favorite in the xxx place?? Xxx
Name = input ("Please enter your name:") address = input ("Please enter place:") hobby = input ("Please enter hobby:") print ("Dear and amiable {name}, favorite {hobby}" in {address}. Format (name=name,address=address,hobby=hobby))

The third piece of Python basics

Related Article

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.