In fact, these tips are really useful, and you can use them when it comes to crunch time!

Boolean type

Python supports Boolean data. Boolean types have only True and False values, but Boolean types have the following operations.

1. And operation: Evaluates to True only if both booleans are True.

Example:

True and True # ==> True
True and False # ==> False
False and True # ==> False
False and False # ==> False
Copy the code

2. Or operation: As long as one of the booleans is True, the result is True.

Example:

True or True # ==> True
True or False # ==> True
False or True # ==> True
False or False # ==> False
Copy the code

3. Non-operations: change True to False, or change False to True.

Example:

not True # ==> False
not False # ==> True
Copy the code

Boolean operations are used in computers to make conditional judgments. Depending on the result of the operation being True or False, the computer can automatically execute different subsequent code.

In Python, Booleans can also perform and, OR, and NOT operations with other data types.

Example:

# Boolean type
a = True
print(a and 'a=T' or 'a=F')
Copy the code

The result is as follows.

a=T
Copy the code

The result is not a Boolean, but the string a=T. Why is that? Since Python treats 0, empty strings, and None as False, and all other numeric and non-empty strings as True, True and ‘a=T’ evaluates to ‘a=T’. ‘A =T’ or ‘a=F’, so it’s still ‘a=T’.

To explain the above results, an important rule of AND and or operations is referred to: the short-circuit operation. The short circuit operator means that the expression around the operator is evaluated only when it needs to be evaluated. For example, if x or y is evaluated from left to right, Python first tests the truth value of expression x. If x is true, then by the nature of the OR operator, regardless of the bool result of y, the result of the operator is expression X, and expression y is not evaluated.

If a is False when we evaluate a and b, then by the and algorithm the result must be False, so return a; If a is True, the entire calculation must depend on B, so return B.

When evaluating a or b, if a is True, then the result must be True according to the or algorithm, so return a; If a is False, the result must depend on B, so return B.

So when the Python interpreter does a Boolean operation, as long as it can determine the result in advance, it does not go back and returns the result.

String type

What is a string

A string is a series of characters. In Python, the contents of single, double, or triple quotes are strings. If the string contains either single or double quotation marks, you can use “\” to escape characters in the string.

Example:

# Text inside single quotes is a string'I am a boy# Double quotes are the same as single quotes. Single quotes are recommended
"Welcome to the Python field."
# A string represented by triple quotes, usually a long text
# Triple quotes are used to write text comments
' ''Our first project in the field is' How to Get started with Python in 7 days'. We'll schedule the material for each day, and it'll only take about 40 minutes to do it. After that, remember to write your homework and submit it to Knowledge Planet.' '
# Transform string (\n)
command = 'Let\'s go!'
print('\n Output with escape characters:',command)
Copy the code

The result is as follows.

Use the escape character to print: Let's go!
Copy the code

Basic usage of strings

1. Add a blank

In programming, some blank output is intended to be easy to read. Common Python methods for adding whitespace are tabs (\t), Spaces, or newlines (\n). The TAB character means to print the text with two empty Spaces.

Example:

# add whitespace
# Tabs can be combined
print("Welcome to the Python field,\n")
print('\t What aspect of Python would you like to learn, leave a comment. ')
Copy the code

The result is as follows.

Welcome to the Python field. What aspect of Python would you like to learn? Leave a comment.Copy the code

2. Concatenated string

A concatenated string is a combination of two or more strings. This operation is often used in projects. For example, in crawlers, regular expressions of web pages (described later) are too long and can be joined by concatenation. It is also possible to concatenate strings of two variables into one. Python uses the plus sign (+) to concatenate strings.

Example:

# concatenate string
log_1_str = 'The error is a bug.'
log_2_str = ' We should fix it.'
log_str = log_1_str + log_2_str
print('\n Concatenated string is: ',log_str)
Copy the code

The result is as follows.

The error is a bug. We should fix it.Copy the code

Common operations on strings

1. Changes the case of a string

Two nouns you’ll hear a lot in Python are function and method. A function is a separate block of code that does a particular task on its own and can be called; Method is a noun used in object-oriented programming languages. Python is an object-oriented programming language, and object orientation means that everything is an object — you, me, him, people — and a person is an object. People can run, and running is a method, combined with people.run().

Example:

# String case conversion
welcome = 'Hello, welcome to Python practical circle'
# title(), capitalize the first letter of each word
print('\n Capitalize the first letter of each word: ', welcome.title())
# Capitalize (), the first letter of the paragraph
print('\n Capitalized paragraph: ',welcome.capitalize())
# lower(), all lowercase letters
print('\n All lowercase letters: ',welcome.lower())
# upper(), all letters capitalized
print('\n All capitals: ',welcome.upper())
# Uppercase to lowercase, lowercase to uppercase
print('\n Uppercase to lowercase, lowercase to uppercase: ',welcome.swapcase())
# string.isalnum (), which checks whether the String contains all digits or English, returns True if it does, False if it does not, and False if it contains special characters such as symbols or Spaces
print('\n Determines whether the string is all numbers.,welcome.isalnum())
# string.isdigit () to determine if all integers in the String are integers
print('\n Determines whether all integers in the string are integers: ', welcome.isdigit())
Copy the code

The result is as follows.

Capitalize the first letter of each word: Hello, Welcome To Python Practical Circle Capitalize the first letter of each paragraph: Hello, Welcome To Python Practical Circle All letters in lower case: Hello, welcome to Python Practical Circle all letters in uppercase: Hello, Welcome to Python Practical Circle uppercase to lowercase, lowercase to uppercase: HELLO, WELCOME TO pYTHON PRACTICAL CIRCLE Check whether the string is all numbers or English: False Check whether the string is all integers: FalseCopy the code

2. Remove whitespace at both ends of the string

Removing whitespace at both ends of a string is often used in data cleansing. A common operation is to remove Spaces at either end or one end.

Example:

 # delete whitespace at both ends
love_Python = ' Hello, Python Practical Circle '
 # Remove whitespace at both ends of the string
print('Delete whitespace at both ends of string',love_Python.strip())
 # Remove whitespace to the right of the string
print('Remove whitespace to the right of string',love_Python.rstrip())
 # Remove whitespace to the left of the string
 print('Remove whitespace to the left of string',love_Python.lstrip())
Copy the code

The result is as follows.

Python Practical Circle removes Hello from the left side of the string, Python Practical CircleCopy the code

3. Other Matters needing attention

There are a lot of string operations in Python, and these are just some of the common ones. It is important to note that strings in Python do not allow values to be modified, only values to be overwritten. That is, strings can only be reassigned.

Slicing of strings

Slice is a common operation in Python. Slicing a string takes a substring (part of a string) from a string. We define a slice using a pair of square brackets, a start offset, a stop offset, and an optional step.

Grammar: [start:end:step] • [:] Extracts the entire string from start (default position 0) to end (default position -1) • [start:] extracts from start to end • [:end] Extracts from start to end • [:end] Extracts from start to end • [start:end] Extracts from start to end • [start:end] Extracts from start to end • [start:end] Extracts from start to end [start:end:step] Extract a character from start to end-1. The position/offset of the first character on the left is 0, and the position/offset of the last character on the right is -1Copy the code

Example:

# string slice
word = 'Python'
print(word[1:2])
print(word[-2:])
print(word[::2])
print(word[::-1])
Copy the code

The result is as follows.

y
on
Pto
nohtyP
Copy the code

Conversions between types

In Python, data types can be converted to each other, and you can use the type() function to see the type of a variable.

Grammar:type(variable name) to view the data type of the variableCopy the code

The type() function is often used in real projects because you can’t perform operations on variables unless you know what type they are, such as dictionary types and list types. Type conversion is also often used in project practice. For example, the monthly sales of a supermarket is a character type, which can only be converted to a number type for statistics, such as calculating the average, etc. The specific conversion syntax is as follows.

Grammar:

float(a) Convert variable A to a floating point int(b) convert variable B to an integer STR (c) convert variable C to a string where a, b, and c are arbitrary variable typesCopy the code

Example:

' ''Conversions between various data types'' '
print('\n Conversion of various numeric types')
number = 100
The data type of # number is an integer, represented by an int
print(The data type of 'number 'is:')
print(type(number))
Convert integers to floating point numbers
float_number = float(number)
print('\ nFLOAT_number is of the data type :')
print(type(float_number))
Convert an integer to a string
print('\nnumber converted to string type ')
str_number = str(number)
print('str_number is of the data type :')
print(type(str_number))
# convert string to int() or float()
print('\nstr_number converts to numeric type ')
int_str_number = int(str_number)
float_str_number = float(str_number)
print('int_str_number has the data type: ')
print(type(int_str_number))
print(The data type of 'float_STR_number' is:)
print(type(float_str_number))
Copy the code

The result is as follows.

The data type of number is <class'int'> The data type of float_number is: <class'float'> number is converted to a string of the data type str_number: <class'str'> str_number converts to numeric type int_str_number data type: <class'int'> The data type of float_str_number is <class'float'>
Copy the code

There are some other practical skills partners can also leave a message to share with you! Welcome to add!