Article From:https://www.cnblogs.com/MayDayTime/p/9122693.html

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[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, 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:
str[start:end:step]
start: Starting position
end: End position
step:step
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

s1.capitalize()
print(s1) # The output has not changed since the string itself will not change. We need to get it again.
ret1 = s1.capitalize()
print(ret1)
# Conversions of case and case
ret = s1.lower() # Convert all into lowercase
print(ret)
ret = s1.upper() # Convert all to uppercase
print(ret)
# 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")
else:
print("Verification failure")
ret = s1.swapcase() # Conversions of case and case to each other
print(ret)
# 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 = s5.center(10, "*") # Stretch to 10, place the original string in the middle.
print(ret)
# Change the length of tab
s6 = "alex wusir\teggon"
print(s6)
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
print(ret)
ret = s7.lstrip() # Remove the left space
print(ret)
ret = s7.rstrip() # Remove the right space
print(ret)
# 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")
else:
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
print(lst)
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.
print(lst)

3. Formatted output

# Formatted output
s12 = "My name is%s,%d years old this year, I like%s" % ('sylar', 18, 'Jay Chou') # Previous writing
print(s12)
s12 = "My name is {}, this year {} years old, I like {}".format("Jay Chou", 28, "Zhou Runfa") # Positional formatting
print(s12)
s12 = "My name is {0}, {2} years old this year, I like {1}".format("Jay Chou", "Zhou Runfa", 28) # Specified position
print(s12)
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
print(s12)

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

5. Condition judgment

# Condition judgment
s14 = "123.16"
s15 = "abc"
s16 = "_abc!@"
# Whether it is made up of letters and numbers
print(s14.isalnum())
print(s15.isalnum())
print(s16.isalnum())
# Whether it is made up of letters
print(s14.isalpha())
print(s15.isalpha())
print(s16.isalpha())
# Whether it is made up of numbers, do not include a decimal point
print(s14.isdigit())
print(s14.isdecimal())
print(s14.isnumeric()) # This comparison is identified in the Chinese B..
print(s15.isdigit())
print(s16.isdigit())
# 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")
else:
  if s17.count(".") == 1 and not s17.startswith(".") and not s17.endswith("."):
    print("It's a decimal")
  else:
  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
print(ret)

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.
Grammar:
for Variable in can be iterated objects:
pass
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:
print(c)
'''
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
print(count)

 

Similar Posts:

Link of this Article: Python base day03

Leave a Reply

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