Python Basics-03

Source: Internet
Author: User

1.python Basic data Types

(1) int ==> integer. Used primarily for mathematical operations

(2) str ==> string, can save a small amount of data and do the corresponding operation

(3) Bool==> judgment True, false

(4) List==> stores large amounts of data. Use [] to denote

(5) Tuple=> tuple, can not be changed with () indicated

(6) Dict==> dictionary, save the key value pair, the same can save a large amount of data

(7) Set==> collection, save a large amount of data. Can not be repeated. In fact, it is not the dict to save value

2. 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"

3. Index index is the subscript. Remember, the subscript starts at 0

# 0123456 7 8

S1 = "Python's most bull B"

Print (s1[0]) # gets a No. 0

Print (s1[1])

Print (s1[2])

Print (S1[3])

Print (S1[4])

Print (S1[5])

Print (S1[6])

Print (S1[7])

Print (S1[8])

# print (s1[9]) # No 9, out of bounds. Will error

Print (S1[-1]) # 1 indicates the reciprocal.

Print (S1[-2]) # second from the bottom

4. slices We can use subscript to intercept the contents of some strings.

Syntax: Str[start:end]

Rule: Gu Tou disregard butt, starting from start intercept. Intercept to the end position. But does not include end

S2 = "Python's most bull B"

Print (S2[0:3]) # from 0 gets to 3. does not contain 3. Results: PYT

Print (S2[6:8]) # Results most cattle

Print (S2[6:9]) # Max is 8. But according to Gu Tou disregard butt, want to fetch 8 must give 9

Print (S2[6:10]) # If the right is past the maximum value. Equivalent to obtaining the last

Print (s2[4:]) # If you want to get to the end. Then the last value can not be given.

Print (s2[-1:-5]) # from-1 get to-5 This is not getting any results. Number from 1 to the right. How can you count-5?

Print (s2[-5:-1]) # Bull B, fetch the data. But. Gu Tou disregard Butt. How to take the last one?

Print (s2[-5:]) # Nothing is written, it's the end.

Print (S2[:-1]) # This is the first one to take to the bottom.

Print (s2[:]) # Output AS-is

5. Skip The Intercept

# Jump, Step

Print (S2[1:5:2]) # from the first start fetch, take to 5th, every 2 fetch 1, Result: YH, analysis: 1:5=> Ytho = YH

Print (S2[:5:2]) # from the beginning to the fifth one. Take one of every two

Print (S2[4::2]) # starts at 4 and takes the last. Take one of every two

Print (S2[-5::2]) # from 5 to last. Take one per two

Print (s2[-1:-5]) # -1:-5 nothing. Because it is obtained from left to right.

Print (s2[-1:-5:-1]) # step is-1. And then you get the value from right to left.

Print (s2[-5::-3]) # starts at the bottom of the 5th. To the very beginning. Fetch one per 3, result Oy

6. If the step size is an integer, take it 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: Step

7. how to manipulate strings

Remember that a string is an immutable object, so any action will have no effect on the original string.

(1) Capitalization

S1.capitalize ()

Print (S1) # The output has not changed. Because the string itself is not changed. We need to get it back.

Ret1 = S1.capitalize ()

Print (RET1)

Uppercase and lowercase conversions

ret = S1.lower () # Convert all to lowercase

Print (ret)

ret = S1.upper () # All converted to uppercase

Print (ret)

# Apply, verify that the user entered the verification code is legitimate

Verify_code = "Abde"

User_verify_code = input ("Please enter the CAPTCHA:")

If verify_code.upper () = = User_verify_code.upper ():

Print ("Verification succeeded")

Else

Print ("Validation failed")

ret = S1.swapcase () # Uppercase and lowercase conversions

Print (ret)

Not used

ret = S1.casefold () # converted to lowercase, and lower difference: lower () support for some characters is not good enough. Casefold () is valid for all letters. Like some words from Eastern Europe.

Mother

Print (ret)

S2 = "Бb?" # Russian Virtues

Print (s2)

Print (S2.lower ())

Print (S2.casefold ())

Each letter that is separated by a special character is capitalized in the first letter

S3 = "Alex Eggon,taibai*yinwang_ Twist Vine"

ret = S3.title () # Alex Eggon,taibai*yinwang_ Twist Vine

Print (ret)

Chinese is also considered a special character

S4 = "Alex old boy Wusir" # Alex old boy Wusir

Print (S4.title ())

(2) Che cut away

Center

S5 = "Jay Chou"

ret = S5.center (10, "*") # is stretched to 10 and the original string is placed in the middle. The rest of the position is mended *

Print (ret)

# Change the length of the tab

S6 = "Alex Wusir\teggon"

Print (S6)

Print (S6.expandtabs ()) # can change the length of \ t, the default length is changed to 8

Go to Space

S7 = "Alex Wusir haha"

ret = S7.strip () # Remove the left and right sides of the space

Print (ret)

ret = S7.lstrip () # Remove left space

Print (ret)

ret = S7.rstrip () # Remove the right space

Print (ret)

# app, impersonate user login. Ignore user-entered spaces

Username = input ("Please enter user name:"). Strip ()

Password = input ("Please enter password:"). Strip ()

If username = = ' Alex ' and password = = ' 123 ':

Print ("Login Successful")

Else

Print ("Login Failed")

S7 = "Abcdefgabc"

Print (S7.strip ("abc")) # DEFG can also specify the elements to be removed,

String substitution

S8 = "Sylar_alex_taibai_wusir_eggon"

ret = S8.replace (' Alex ', ' Golden Horn King ') # replace Alex with King Horn

Print (S8) # Sylar_alex_taibai_wusir_eggon Remember that a string is an immutable object. All operations are to produce a new string return

Print (ret) # sylar_ Golden Horn King _taibai_wusir_eggon

ret = s8.replace (' i ', ' SB ', 2) # Replace I to SB, replace 2

Print (ret) # Sylar_alex_tasbbasb_wusir_eggon

(3) String Cutting

S9 = "Alex,wusir,sylar,taibai,eggon"

LST = S9.split (",") # string cut, according to, to be cut

Print (LST)

S10 = "" "Poet

Scholars

Exclamation number

Slag residue "" "

Print (S10.split ("\ n")) # Cut with \ n

(4) Pits

S11 = "Silver king haha silver king hehe Silver King Roar roar Silver King"

LST = S11.split ("Silver King") # [', ' haha ', ' hehe ', ' roar ', '] if the cutter is at the left and right ends. Then there must be an empty string. Deep Pit Please note

Print (LST)

(5) formatted output

# Formatted output

S12 = "My name is%s, this year%d years old, I like%s"% (' Sylar ', 18, ' Jay ') # before the wording

Print (S12)

S12 = "I call {}, this year {} years old, I like {}". Format ("Jay Chou", 28, "Chow Yun-Fat") # Formatted by location

Print (S12)

S12 = "My name is {0}, this year {2} years old, I like {1}". Format ("Jay Chou", "Chow Yun-Fat", 28) # Specify location

Print (S12)

S12 = "My Name {name}, this year {age}, I like {singer}". Format (name= "Jay Chou", singer= "Chow Yun-Fat", age=28) # Specify Keywords

Print (S12)

(6) Find

S13 = "My name is Sylar, I like Python, Java, C and other programming languages."

Ret1 = S13.startswith ("Sylar") # to determine whether to start with Sylar

Print (RET1)

Ret2 = S13.startswith ("My Name is Sylar") # to see if I start with my name Sylar

Print (Ret2)

Ret3 = S13.endswith ("language") # Does it end with ' language '

Print (RET3)

Ret4 = S13.endswith ("language.") # whether with ' language. ' End

Print (RET4)

Ret7 = S13.count ("a") # Find the number of occurrences of "a"

Print (RET7)

Ret5 = S13.find ("Sylar") # Find where ' Sylar ' appears

Print (RET5)

Ret6 = S13.find ("Tory") # Find the location of ' Tory ' if not returned-1

Print (RET6)

Ret7 = S13.find ("A", 8, 22) # Slice Find

Print (RET7)

Ret8 = S13.index ("Sylar") # Quest lead position. Attention. If the index is not found. Program will error

Print (RET8)

(7) Conditional Judgment

# Conditional Judgment

S14 = "123.16"

S15 = "ABC"

s16 = "[Email protected]"

# Is it made up of letters and numbers ?

Print (S14.isalnum ())

Print (S15.isalnum ())

Print (S16.isalnum ())

# is it made up of letters?

Print (S14.isalpha ())

Print (S15.isalpha ())

Print (S16.isalpha ())

# Whether it consists of numbers, excluding decimal points

Print (S14.isdigit ())

Print (S14.isdecimal ())

Print (S14.isnumeric ()) # This compares Bull B. Chinese are recognized.

Print (S15.isdigit ())

Print (S16.isdigit ())

# Practice. Use an algorithm to determine whether a string is a decimal

S17 = "-123.12"

S17 = S17.replace ("-", "") # Replace minus sign

If S17.isdigit ():

Print ("is an integer")

Else

If S17.count (".") = = 1 and not S17.startswith (".") and not S17.endswith ("."):

Print ("Is decimal")

Else

Print ("Not decimal")

(8) calculate the length of a string

S18 = "I am your eye, I am a"

ret = Len (s18) # Calculates the length of a string

Print (ret)

Note: Len () is a python built-in function. So the access method is not the same. You just remember Len () and print ().

(9) Iteration

We can use a For loop to facilitate (get) every character in a string

Grammar:

The for variable in can iterate over the object:

Pass

An iterative object: an object that can take a value outward

S19 = "Hello everyone, I am vue, the front-end of the children." How you doing? "

# using the While loop

index = 0

While index < Len (S19):

Print (S19[index]) # using indexed tiles to complete the search of characters

index = index + 1

# for Loop, take each character in the S19 and assign it to the previous C

For C in S19:

Print (c)

‘‘‘

In there are two ways to use:

1. In for. is to assign each element to an assignment to the preceding variable.

2. Not in for. Determine if XXX appears in Str.

‘‘‘

Print (' VUE ' in S19)

# practice, calculated in the string "I am Sylar, I ' M years old, I had 2 dogs!"

S20 = "I am Sylar, I ' M years old, I has 2 dogs!"

Count = 0

For C in S20:

If C.isdigit ():

Count = Count + 1

Print (count)

Python Basics-03

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.