Python study notes - some functions

This article corresponds to the Python exercises on Touge: https://www.educoder.net/paths/pn7qklv9

Basic knowledge 1:

input() function

The input() function obtains user input from the console. No matter what the user enters on the console, the input() function returns the result as a string.

  1. name=input()//将用户输入的字符串存储到name变量中
    name = input () //Store the string entered by the user into the name variable

Input: Zhang San , then the value stored in the name variable is "Zhang San".

Before obtaining user input, the input() function can contain some prompt text. The method of use is as follows:

  1. <Variable>=input(<Prompt text>)

For example:

name=input("请输入一个人的名字:")
country=input("请输入一个国家的名字:")

print() function

When the print() function outputs pure character information, you can directly pass the content to be output to the print() function, such as:

print("祖国,你好!")

Output: Hello, motherland!

When outputting variable values, you need to use formatted output , and use the format() method to organize the variables to be output into the desired output format, such as:

name=input("请输入一个人的名字:")
country=input("请输入一个国家的名字:")
print("{}来自于{}".format(name,country))

Input: " Zhang San China "   

Output: Zhang San is from China

enter

Use the input function to obtain user input. On the console window, enter a line of string and assign it to a variable in the form of variable = input() :

str1 = input()
print("输入的是%s" % str1)

If you enter hello and then press Enter, the output is: hello is entered .

You can also add some prompt information within the brackets of input() :

str1=input("请输入:")
print("输入的是%s" % str1)

After running, it will first display please enter:, enter the data hello and then press Enter, you will get the output: the input is hello , and the entire content displayed on the console is:

Please enter:helloThe  input is hello

 output

The basic use of the print function has appeared many times in previous levels. Put the content to be output within the brackets of print() to output:

print("hello world")

The result is: hello world

The print function can output multiple contents at the same time, just put them together in the brackets of print and separate them with commas:

print("hello","world")

Result obtained: hello world

It is worth noting that there will be spaces separating multiple contents output at the same time .

Similar to C/C++'s printf , Python's print can also achieve formatted output by using the % operator, which treats the string on the left as a format string and substitutes the parameters on the right into the format string:

print("100 + 200 = %d" % 300) #左边的%d被替换成右边的300
print("A的小写是%s" % "a") #左边的%s被替换成右边的a

The result is:

100 + 200 = 300  The lower case of A is a

If you want to bring in multiple parameters, you need to wrap the multiple parameters with () and separate them with commas . The order of the parameters should correspond to the order in the format string :

  1. print("%d + %d = %d" % (100,200,300))
  2. print("%s %s" % ("world","hello"))

The result is:

100 + 200 = 300 world hello

Example: Please turn it into a simple four arithmetic operations on two integers:

c language programming implementation:

#include<stdio.h>
int main()
{
	int a, b;
	printf("请输入整数a的值:"); 
	scanf("%d", &a);
	printf("请输入整数b的值:"); 
	scanf("%d", &b);

	printf("%d + %d = %d\n", a, b, a + b);  //参数和双引号之间是逗号分隔;
		printf("%d - %d = %d\n", a, b, a - b);
			printf("%d * %d = %d\n", a, b, a * b);
				printf("%d + %d = %f", a, b, (float)a / b); //隐式类型转换
	return 0;
}

Python programming implementation:

a = int(input("请输入整数a的值:"))
b = int(input("请输入整数b的值:"))
print("%d + %d = %d" %(a,b,a+b))  #双引号 和参数之间没有逗号分隔
print("%d - %d = %d" %(a,b,a-b))
print("%d * %d = %d" %(a,b,a*b))
print("%d + %d = %f" %(a,b,a/b))

Comparing the two languages, we can know that the printf() function of C language and the print function of Python are similar, but there are also differences. The double quotation marks and the separation between parameters are different between the two.

Python can also write the expression of the four arithmetic operations like this (take a + b as an example): print(a,"+",b,"=",a+b)

The meaning of different placeholders in the format string :

%s: as string 

%d: as a signed decimal integer

 %u: as an unsigned decimal integer 

%o: as an unsigned octal integer 

%x: As an unsigned hexadecimal integer, a~f are in lowercase form 

%X: As an unsigned hexadecimal integer, A to F are in uppercase form 

%f: as a floating point number 

%e, %E: As a floating point number, using scientific notation

 %g, %G: as floating point number, using least significant digits

You can search for more usages on the Internet.

Note:  The print function will wrap the data after outputting it. If you do not want to wrap the data, you need to specify end="" :

  1. print("hello" , end="")
  2. print("world" , end="")

Result obtained: helloworld

 {}.format(): () without quotation marks means it is a variable, otherwise it is a string

The basic syntax is to use  {}  and  :  to replace the previous  % . {} indicates the position of the content to be displayed in the format, and : is equivalent to %;

Example:

>>>"{} {}".format("hello", "world")   #不设置指定位置,按默认顺序

 'hello world' 

>>> "{0} {1}".format("hello", "world")   #设置指定位置 

'hello world' 

>>> "{1} {0} {1}".format("hello", "world")  #设置指定位置 

'world hello world'

Number formatting

>>> print("{:.2f}".format(3.1415926))
输出:3.14

Python string

The length of the string Hello world in the above figure is 11 (note that a space is also a character). In forward increment, the serial number of the leftmost character H is 0 , and it increases sequentially to the right. The serial number of the rightmost character d is 11-1=10 ; The reversely decreasing sequence number starts with the rightmost character d , whose sequence number is -1 , and decreases in sequence to the left, where the leftmost character H's sequence number is -11 . Both methods of indexing characters can be used simultaneously.

( Analogous to arrays in C language ) Python strings also provide interval access , using the [N:M] format to represent substrings from N to M (excluding M ) in the string , where N and M are strings . The index sequence number can be a mixture of forward increasing sequence numbers and reverse decreasing sequence numbers. If the N or M index is missing from the representation , it means that the starting or ending index value of the string is set to the default value .

Examples are as follows:

>>>name="Python语言程序设计"
>>>name[0]
'P'

>>>print(name[0],name[7],name[-1])
P 言 计
>>>print(name[2:-4])
thon语言

>>>print(name[:6])  #缺少左值,所以是从开始到第6个
Python

>>>print(name[6:])  #缺少右值,所以是从第6个到结束
语言程序设计
>>>print(name[:])
Python语言程序设计

String conversion

The input function receives the string input by the user. At this time, it cannot be used as an integer or decimal for mathematical operations. You need to use a function to convert the string into the desired type.

  • To convert to an integer, use the int() function:
    num1 = int(str)
  • To convert to decimal, use float() function:
    f1 = float(str)
  • str = input()
    num1 = int(str)
    f1 = float(str)
    print("整数%d,小数%f" % (num1,f1))

    If you enter 10, the output is: integer 10, decimal 10.000000 .

indentation

Python is different from C-like languages ​​such as C/C++ and Java. Python uses indentation to represent code blocks. The number of indented spaces can be determined by personal habits, but the number of indented spaces for the same code block must be the same.

if True:
    print("true")
    print("true")
else:
 print("false")
 print("false");

The if part and else part of the above program have different indentations, but the indentation is the same within the respective code blocks, so it is a correct program.

if True:
   print("true")
  print("true")

The if part of this program is indented differently, so it is a wrong program.

multi-line statement

Python code is generally one statement per line , and the semicolon after the statement  can be added or not. But if you want to write multiple statements in one line, you need to  separate each statement with a semicolon ;

print("hello")
print("world");

print("hello");print("world")

The above three lines (four statements) are all correct.

identifier

Identifiers are various names used in programs, such as variable names, constant names, class names, etc. In Python, the requirements for identifier format are similar to those in C/C++, Java, etc.:

  • The first character must be a letter of the alphabet or the underscore  _  ;
  • The other parts of the identifier consist of letters, numbers and underscores;
  • Identifiers are case-sensitive;
  • The identifier cannot be the same as a reserved word.

for example:

num1 = 1
float1 = 0.5
true = True #这个 true 虽然字面上的意思与值“True”相同,但 python 对大小写敏感,所以也是正确的
str1 = "hello"

These are correct identifiers.

and:

1value = 1 #开头不能是数字
value0.1 = 0.1 #标识符中间只能是数字,字母,下划线
if = True #与保留字if重名

are incorrect identifiers.

reserved words

Reserved words are keywords, which are words used internally in the Python language and represent certain semantics. For example: and, class, if, else, etc. Reserved words cannot be used as identifiers and are used in variable names, constant names, class names, etc. Python's standard library provides a keyword module that can output all keywords of the current version:

import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Comments are descriptions of program code. They are generally used by programmers to understand the code and are not part of the program.

Single-line comments in Python start with # :

#这是一个注释1
print("python") #这是一个注释2
#print("python2")

The result of running is: python

Multi-line comments can use multiple # , or you can use a pair of ''' (three single quotes) or """ (three double quotes) to wrap the content to be commented:

#使用多个#
#作注释

'''
用三个单引号
作注释
'''

"""
用三个双引号
作注释
"""

Basic knowledge 2:——Basic data types

String processing

Used in Python +to merge two strings, this method of merging strings is called concatenation. Its basic syntax is as follows:

  1. result_string = source_string1 + source_string2

in:

  • source_string1: The first string to be merged;

  • source_string2: The second string to be merged;

  • result_string: The merged string.

Note: If necessary, you can add corresponding spaces between the two strings, see the example below for details. For example, to concatenate the first and last name into a full name:

# coding=utf-8

# 将姓氏和名字分别保存在两个变量中
first_name = 'Zhang'
last_name = 'san'

# 将姓氏和名字拼接,将结果存储在full_name变量中
full_name = first_name + " " + last_name
print(full_name)

character conversion

The Python standard library provides a series of functions for string processing. The small goal is to let everyone learn and master the usage of len()upper(), lower()and strip()functions among the common string methods in Python , and complete the corresponding string processing tasks.

Note: upper(), lower(), strip() are all post-functions, usage: string.xxx(), where xxx is the corresponding function

Get string length

Python provides len()functions to calculate and return the length of a string, that is, the number of individual elements in the string. Its basic syntax is as follows:

  1. length = len(target_string)

in:

  • target_string: target string variable;

  • length: A variable that holds the length of the string;

  • len: Syntax keyword to get the length of a string.

Specific usage examples are given below:

# coding=utf-8

# 创建一个字符串变量,获取其长度并打印出来
color = 'It is red'
length = len(color)
print (length)

# 直接在len函数中引入字符串内容获得其长度,然后打印出来
print(len('This is a circle!'))

Output result:

  1. 9
  2. 17

Note: As you can see from the output, spaces also occupy the position of a character element.

Case conversion

Python provides upper()and lower()methods to convert strings to uppercase and lowercase. Among them, upper()all characters in the string will be converted to uppercase, lower()and all characters in the string will be converted to lowercase . In addition, Python also thoughtfully provides a title()method to change the first letters of all words in a string to uppercase, while other letters remain lowercase. The specific syntax of each method is as follows:

  1. # 将源字符串转换为大写并存入upper_string变量
  2. upper_string = source_string.upper()
  3. # 将源字符串转换为小写并存入lower_string变量
  4. lower_string = source_string.lower()
  5. # 将源字符串每个词首字母转换为大写并存入title_string变量
  6. title_string = source_string.title()

Among them, source_stringis the source string to be processed. Specific usage examples are as follows:

# coding=utf-8

# 创建一个字符串say_hello
say_hello = 'Dear my Daughter'

# 使用upper()方法对say_hello字符串进行处理
upper_say_hello = say_hello.upper()

# 使用lower()方法对say_hello字符串进行处理
lower_say_hello = say_hello.lower()

# 使用title()方法对say_hello字符串进行处理
title_say_hello = say_hello.title()

# 打印输出四个字符串
print (say_hello+"\n")
print (upper_say_hello+"\n")
print (lower_say_hello+"\n")
print (title_say_hello+"\n")

Output result:

  1. Dear my Daughter
  2. DEAR MY DAUGHTER
  3. dear my daughter
  4. Dear My Daughter

Note: It can be seen from the above printing results that the call of the above method will not affect the original say_hellostring, and the converted string will be stored in a new variable.

Remove leading and trailing spaces from string

Python provides strip()a method to remove all spaces on both sides of a string (excluding internal spaces) . Using this method, you can also remove specific characters specified on both sides by specifying parameters.

Note: When specifying parameters, if the parameters are multiple characters, this method will compare the multiple characters one by one and delete them (case-sensitive) until there are no matching characters on both sides. However, this method has no effect on characters in the middle of the string.

Its basic syntax is as follows:

  1. strip_string1 = source_string.strip()
  2. string_strip2 = source_string.strip(target_char)

in:

  • source_string: The source string to be processed;

  • strip_string1and strip_string2: processed string;

  • target_char: Specific characters that need to be removed from the beginning and end of the source string.

Specific usage examples are as follows:

# coding = utf-8

# 创建一个字符串hello_world
hello_world = ' **The world ** is big!* '

# 利用strip()方法处理hello_world字符串
blank_hello_world = hello_world.strip()
char_hello_world = hello_world.strip('TH *')

# 打印输出转换后的字符串
print(blank_hello_world)
print(char_hello_world)

Output result:

  1. **The world ** is big!*
  2. he world ** is big!

Output result analysis:

  • As you can see from the first line of print results, strip()the method removes all spaces at the beginning and end of the source string, but does not remove the spaces in the middle of the string ;

  • It can be seen from the second line of the printed structure that the method removes strip()all spaces and * characters from the beginning and end of the source string, but the header in the source string is not removed because it is lowercaseTh .

String search and replace

Learn and master the commonly used string methods in Python, including string search (find()), string segmentation (split()), string replacement (replace()), etc.

Usage: string.xxx(), xxx is the corresponding function

String search

Python provides a built-in string search methodfind() that can be used to find substrings in a longer string. If there are one or more substrings in the string, this method returns the leftmost index of the first substring. If no substring that meets the conditions is found, it returns -1. find()The basic usage syntax of the method is as follows:

  1. source_string.find(sub_string)

in:

  • source_string: source string;

  • sub_string: The target substring to be checked;

  • find: Syntax keyword for string search method.

For example, to find the position of two words in a string:

# coding=utf-8

# 创建一个字符串
source_string = 'The past is gone and static'

# 查看"past"在source_string字符串中的位置
print(source_string.find('past'))

# 查看"love"在source_string字符串中的位置
print(source_string.find('love'))

Output result:

  1. 4
  2. -1

String replacement

Python provides replace()methods to replace substrings in a given string. Its basic usage syntax is as follows:

  1. source_string.replace(old_string, new_string)

in:

  • source_string: The source string to be processed;

  • old_string: The old string to be replaced;

  • new_string: New string to replace;

  • replace: Syntax keyword for string replacement method.

For example, in the following string, smallreplace substring with bigsubstring:

# coding = utf-8

# 创建一个字符串circle
source_string = 'The world is big'

# 利用replace()方法用子串"small"代替子串"big"
print(source_string.replace('big','small'))

Output result:

  1. The world is small

String splitting

Python provides split()methods to implement string splitting. This method splits a string into a character list based on the provided delimiter. If no delimiter is provided, the program will default to using spaces (tabs, newlines, etc.) as the delimiter. Its basic usage syntax is as follows:

  1. source_string.split(separator)

in:

  • source_string: The source string to be processed;

  • separator: separator;

  • split: Keyword for string splitting method.

For example, use +, /and spaces as delimiters to split a string:

# coding = utf-8

# 待处理字符串source_string
source_string = '1+2+3+4+5'

# 利用split()方法,按照`+`和`/`对source_string字符串进行分割
print(source_string.split('+'))
print(source_string.split('/'))

Output result:

  1. ['1', '2', '3', '4', '5']
  2. ['1+2+3+4+5']

Guess you like

Origin blog.csdn.net/qq_29992017/article/details/122690666