Article From:

One.Python basic data type
1. int ==> Integer. Used primarily for mathematical operations
2. str ==> String can save a small amount of data and perform corresponding operations.
3. bool==>Judge true and false, True, False
4. list==> Store a lot of data.
5. tuple=> A tuple can not be changed with () representation
6. dict==> Dictionary, save key value pairs, the same can save a lot of data.
7. set==> Collection, saving large amounts of data. Can not be repeated. In fact, it does not save value’s dict.
Two. Integer (int)
In python3, all integers are int types. But in python2, if the data volume is large, the long type will be used. There is no long type in python3.
An operation that can be performed by an integer:
bit_length(). Calculate the length of integer binary code occupied in memory.

Three. Boolean value (bool)
The value is only True, and the value of the False. bool is not operated.
Conversion problem:
str => int int(str)
int => str str(int)
int => bool bool(int). 0It is False non 0 is True
bool=>int int(bool) TrueIt’s 1, False is 0
str => bool bool(str) The empty string is False, no space is True
bool => str str(bool) Convert the bool value to the corresponding “value”
Four. String (STR)
String the characters together. In Python, the contents that are drawn by ‘,’, ‘and’ are called strings.
4.1 Slicing and indexing
1. Index. Index is subscript. Remember, subscript starts from 0.

# 0123456 7 8
s1 = "pythonNiu B"
print(s1[0]) # Get zeroth
# print(s1[9]) # No 9, cross the border. It will be wrong
print(s1[-1]) # -1 Represents the reciprocal.
print(s1[-2]) # Second to last

2. Slice, we can use the subscript to intercept the contents of some strings.
Syntax: str[start: end]
Rule: ignore the buttocks and start interception from start. Intercept to end position, but do not include end.

s2 = "pythonNiu B"
print(s2[0:3]) # Getting from 0 to 3. does not contain 3. results: PYT
print(s2[6:8]) # The best result
print(s2[6:9]) # The maximum is 8., but according to Gu tou's disregard for buttocks, it is necessary to give 9 to get 8.
print(s2[6:10]) # If the right side has passed the maximum value, it is equivalent to getting the last.
print(s2[4:]) # If you want to get to the end, the last value can not be given.
print(s2[-1:-5]) # From -1 to -5, you won't get any results. From -1 to the right, you can't count -5.
print(s2[-5:-1]) # The cow has got the data. But how can we get the last one?
print(s2[-5:]) # Nothing to write is the last
print(s2[:-1]) # This is the first one to take the countdown
print(s2[:]) # Original output

Jump and intercept

# Jump, step
print(s2[1:5:2]) # From the first one, we take fifth, and take 2 out of every 2. The result is: YH, analysis: 1:5=> ytho => YH
print(s2[:5:2]) # From the beginning to the fifth. Take one for every two.
print(s2[4::2]) # From 4 to the end. One for every two.
print(s2[-5::2]) # Take from -5 to the end. Take one for every two.
print(s2[-1:-5]) # -1:-5Nothing. Because it's got from left to right.
print(s2[-1:-5:-1]) # The step is -1. at this time, from right to left
print(s2[-5::-3]) # Start from the bottom fifth. To the very beginning, take one out of every 3. The result is oy.

Step size: if it is an integer, then take it from left to right. If it is negative, then take it from right to left. The default is 1.
Slicing Grammar:
start: Starting position
end: End position
4.2 The related operation method of string
Remember, string is an immutable object, so any operation has no effect on the original string.
1. Turn around

print(s1) # The output has not changed since the string itself will not change. We need to get it again.
ret1 = s1.capitalize()
# Conversions of case and case
ret = s1.lower() # Convert all into lowercase
ret = s1.upper() # Convert all to uppercase
# Application to verify the validity of the authentication code for user input
verify_code = "abDe"
user_verify_code = input("Please enter the verification code:")
if verify_code.upper() == user_verify_code.upper():
print("Verification success")
print("Verification failure")
ret = s1.swapcase() # Conversions of case and case to each other
# Not commonly used
ret = s1.casefold() # Conversion to lowercase, and lower: lower () is not good enough for some characters. Casefold () is valid for all letters.
For example, some letters in Eastern Europe
print(ret) s2 = "БBß" # Russian virtues print(s2) print(s2.lower()) print(s2.casefold()) # Each letter is capitalized with special characters. s3 = "alex eggon,taibai*yinwang_Rattan" ret = s3.title() # Alex Eggon,Taibai*Yinwang_Rattan print(ret) # Chinese is also a special character s4 = "alexOld boy wusir" # AlexOld boy Wusir print(s4.title())

2. Cut off

# Middle
s5 = "Jay Chou"
ret =, "*") # Stretch to 10, place the original string in the middle.
# Change the length of tab
s6 = "alex wusir\teggon"
print(s6.expandtabs()) # The length of the \t can be changed, and the default length is changed to 8
# Go to the space
s7 = " alex wusir haha "
ret = s7.strip() # Remove the space between the left and the right
ret = s7.lstrip() # Remove the left space
ret = s7.rstrip() # Remove the right space
# Application to simulate user login. Ignore the space entered by users.
username = input("Please enter the username:").strip()
password = input("Please input a password:").strip()
if username == 'alex' and password == '123':
print("Login success")
print("Login failure")
s7 = "abcdefgabc"
print(s7.strip("abc")) # defg You can also specify the elements to be removed.
# String substitution
s8 = "sylar_alex_taibai_wusir_eggon"
ret = s8.replace('alex', 'Qwedcxza') # Replace Alex with King King
print(s8) # sylar_alex_taibai_wusir_eggon Remember, strings are immutable objects. All operations are generated by returning new strings.
print(ret) # sylar_King Kok king _taibai_wusir_eggon
ret = s8.replace('i', 'SB', 2) # Replace I with SB and replace 2
print(ret) # sylar_alex_taSBbaSB_wusir_eggon
# String cutting
s9 = "alex,wusir,sylar,taibai,eggon"
lst = s9.split(",") # String cutting, based, cutting
s10 = """PoetScholarExclamatory markSlag slag"""
print(s10.split("\n")) # Cutting with \n
# pit
s11 = "The Silver King, the king haha, the Silver King roar the Silver King"
lst = s11.split("King of silver") # ['', 'Ha ha, ha ha, roar, and if the cutter is at the left and right ends, there will be an empty string.

3. Formatted output

# Formatted output
s12 = "My name is%s,%d years old this year, I like%s" % ('sylar', 18, 'Jay Chou') # Previous writing
s12 = "My name is {}, this year {} years old, I like {}".format("Jay Chou", 28, "Zhou Runfa") # Positional formatting
s12 = "My name is {0}, {2} years old this year, I like {1}".format("Jay Chou", "Zhou Runfa", 28) # Specified position
s12 = "My name is {name}, {age} years old this year, I like {singer}".format(name="Jay Chou", singer="Zhou Runfa", age=28) # assign key words

4. lookup

s13 = "My name is Sylar, I like python, Java, C and other programming languages."
ret1 = s13.startswith("sylar") # Judge whether to begin with Sylar
ret2 = s13.startswith("My name is Sylar") # Judge whether I start with Sylar
ret3 = s13.endswith("language") # Do you end up with a 'language'
ret4 = s13.endswith("Language.") # Do you end up at the end of the 'language.'
ret7 = s13.count("a") # Find the number of times that "a" appears
ret5 = s13.find("sylar") # Locate the location of the'sylar'
ret6 = s13.find("tory") # Find the location of the'tory'if you do not return to -1
ret7 = s13.find("a", 8, 22) # Slicing
ret8 = s13.index("sylar") # Index location. Note. If the index is not found, the program will report the error.

5. Condition judgment

# Condition judgment
s14 = "123.16"
s15 = "abc"
s16 = "_abc!@"
# Whether it is made up of letters and numbers
# Whether it is made up of letters
# Whether it is made up of numbers, do not include a decimal point
print(s14.isnumeric()) # This comparison is identified in the Chinese B..
# Exercise. Use algorithm to determine whether a string is decimal.
s17 = "-123.12"
s17 = s17.replace("-", "") # Replace a negative sign
if s17.isdigit():
print("It is an integer")
  if s17.count(".") == 1 and not s17.startswith(".") and not s17.endswith("."):
    print("It's a decimal")
  print("Not a decimal")

6. Calculating the length of a string

s18 = "I'm your eye, and I'm a"
ret = len(s18) # Calculating the length of a string

Note: len () is built-in function of Python. So the access mode is different. You just remember len () and print ().

7. iteration
We can use the for loop to facilitate (get) every character in the string.
for Variable in can be iterated objects:
Iterable objects: objects that can be taken out one by one.

s19 = "Hello, everyone. I am VUE, children at the front end. How are you?"
# While cycle
index = 0
while index < len(s19):
print(s19[index]) # Using index slices to complete the search of characters
index = index + 1
# forLoop, take every character in S19 and assign it to the front C.
for c in s19:
inThere are two uses:1. in for, each element is assigned to the preceding variable.2. is not in for. Determine whether XXX appears in str.'''
print('VUE' in s19)
# The exercises are calculated in the string "I am Sylar, I'm 14 years old, I have 2 dogs!"
s20 = "I am sylar, I'm 14 years old, I have 2 dogs!"
count = 0
for c in s20:
if c.isdigit():
count = count + 1


Link of this Article: Python base day03

Leave a Reply

Your email address will not be published. Required fields are marked *