current position:Home>[Python basics] explain Python basic functions in detail, including teaching and learning

[Python basics] explain Python basic functions in detail, including teaching and learning

2022-01-31 01:21:41 Dream, killer

「 This is my participation 11 The fourth of the yuegengwen challenge 4 God , Check out the activity details :2021 One last more challenge 」.

Running environment

python:3.8.3
jupyter-notebook : 6.4.0

Be careful : This case can be directly in jupyter-notebook Up operation , But in PyCharm You need to add... To the last sentence of the code print Oh !


I / O function

print()

print() It's definitely the function we use most , He can output directly 、 Specify the interval / Ending characters 、 Save the output to the specified file ( application : Record automation script exception information ) etc. . Here are some common uses .

1️⃣ Direct output

print('hello world')
 Copy code 
output:hello world

2️⃣ Specify the spacing character sep

print('A', 'B', 'C', sep=' Python ')
 Copy code 
output:A Python B Python C

3️⃣ Specify the ending character

print('hello', 'world', end='Python')
 Copy code 
output:hello worldPython

4️⃣ Save the output to outfile.txt In file

print('hello', 'world', sep=' ', file=open('outfile.txt', 'w', encoding='utf-8'))
 Copy code 

input()

input() Can receive user input , And save it as a string .

name = input('name:')
 Copy code 

stay jupyter notebook The effect of execution on may be different from that of other editors , But the operation is after input , Press “ enter ” that will do .


Get data type

type()

type() Returns the data type of the specified value .

type([1, 2])
 Copy code 
output:list

isintance()

isintance() Judge whether the passed in value is of the specified type , return True/False .

isinstance('Python New horizons ', str)
 Copy code 
output:True

String manipulation

str()

str() Converts the specified value to a string type .

str(1.23)
 Copy code 
output:'1.23'

eval()

eval() Convert a string into a valid expression to evaluate or evaluate the result . You can convert strings to lists (list), Tuples (tuple), Dictionaries (dict), aggregate (set) etc. .

res = eval("{'name': 'Python'}")
type(res)
 Copy code 
output:dict

str.capitalize()

capitalize() Returns the uppercase of the first letter in a string , Other lowercase strings

cap_str = 'python New horizons '.capitalize()
cap_str
 Copy code 
output:'Python New horizons '

str.center()

center() Returns a centered string of the specified width , The left and right parts are filled with the specified characters .

  • width: length
  • fillchar: Characters filled in the spare part , By default, spaces are used
center_str = 'Python New horizons '.center(15, "!")
center_str
 Copy code 
output:'!!!Python New horizons !!!'

str.count()

str.count(sub, start, end) return sub stay str Is the number of times , Can pass [start, end] Specified scope , If not specified , The default is to find the entire string .

  • sub: Substring
  • start: Index started , The default is 0
  • end: End index , The default is the length of the string
name = 'python python'
#  For the first time, it is counted according to the default range 'p' Number of occurrences ,
#  The second appointment start=1, That is, start counting from the second character .
name.count('p'), name.count('p', 1)
 Copy code 
output:(2, 1)

str.find() & str.rfind()

1️⃣ find() Scan string from left to right , return sub First occurrence of subscript . Can pass [start, end] Specified scope , If not specified , The default is to find the entire string . If the string is not found at last, it returns -1.

  • sub: Substring
  • start: Where to start searching , The default is 0
  • end: Where to end the search , The default is the length of the string
name = 'Python'
#  Find by default range for the first time 'Py' First occurrence of subscript 
#  The second appointment start=1, That is, start from the second character to find .
name.find('Py'), name.find('Py', 1)
 Copy code 
output:(0, -1)

2️⃣ rfind And find() The usage of is similar to , It's just From right to left Start scanning , That is, scan from the end of the string to the beginning of the string .

name = 'Python'
name.rfind('Py'), name.rfind('Py', 1)
 Copy code 
output:(0, -1)

str.index() & str.rindex()

1️⃣ index() and find() The usage is the same , The only difference is if you can't find sub Will report a mistake .

Example

name = 'Python'
name.index('Py', 0)
 Copy code 
output:0

Example :b:

name = 'Python'
name.index('Py', 1)
 Copy code 
output:ValueError: substring not found

2️⃣ rindex() and index() The usage is the same , But from On the right Start checking , Its query and index() identical .

name = 'Python'
name.rindex('Py', 0)
 Copy code 
output:0

str.isalnum()

isalnum() Determine whether all characters in the string are letters ( Can be Chinese characters ) Or number , yes True , no False, Empty string returns False.

Example

'Python New horizons '.isalnum()
 Copy code 
output:True

Example :b:

'Python-sun'.isalnum()
 Copy code 
output:False
'-' It's the sign , So back False.

str.isalpha()

isalpha() Determine whether all characters in the string are letters ( Can be Chinese characters ), yes True , no False, Empty string returns False.

Example

'Python New horizons '.isalpha()
 Copy code 
output:True

Example

'123Python'.isalpha()
 Copy code 
output:False
It contains numbers , return False

str.isdigit()

isdigit() Determine whether all characters in the string are numbers (Unicode Numbers ,byte Numbers ( Single byte ), Full angle numbers ( Double byte ), Rome digital ), yes True , no False, Empty string returns False.

Example

' Four 123'.isdigit()
 Copy code 
output:False

It contains Chinese characters and numbers , return False


Example

b'123'.isdigit()
 Copy code 
output:True

byte The number returns True .


str.isspace()

The string contains only spaces (\n\r\f\t\v), yes True , no False, Empty string returns False.

Symbol meaning
\n Line break
\r enter
\f Change the page
\t Horizontal tabs
\v Vertical tabs
' \n\r\f\t\v'.isspace()
 Copy code 
output:True

str.join()

join(iterable) Use the specified string as the separator , take iterable All the elements in ( Must be a string ) Merge into a new string .

','.join(['Python', 'Java', 'C'])
 Copy code 
output:'Python,Java,C'

str.ljust() & str.rjust()

1️⃣ ljust() Returns a left aligned string of the specified width

  • width: length
  • fillchar: Characters filled in the left part of the right , By default, spaces are used
ljust_str = 'Python New horizons '.ljust(15, "!")
ljust_str
 Copy code 
output:'Python New horizons !!!!!!'

2️⃣ rjust() Returns a right aligned string of the specified width , And ljust The operation is just the opposite .

  • width: length
  • fillchar: Characters filled in the left space , By default, spaces are used
rjust_str = 'Python New horizons '.rjust(15, "!")
rjust_str
 Copy code 
output:'!!!!!!Python New horizons '

str.lower() & str.islower()

1️⃣ lower() Converts the specified string to lowercase .

lower_str = 'Python New horizons '.lower()
lower_str
 Copy code 
output:'python New horizons '

2️⃣ islower() Determines whether all case sensitive characters in a string are lowercase , yes True , no False, An empty string or a string with no case sensitive characters returns False .

'python-sun'.islower()
 Copy code 
output:True

'python-sun' Case sensitive characters are 'pythonsun', And they are all lowercase , So back True .


str.lstrip() & str.rstrip() & str.strip()

1️⃣ lstrip() It will be intercepted according to the specified character on the left side of the string , If no default is specified, the left margin is intercepted ( Space ,\r,\n,\t etc. ) part .

name = '+++Python New horizons +++'
name.lstrip('+')
 Copy code 
output:'Python New horizons +++'

2️⃣ rstrip() And lstrip() Similar usage , Just intercept the content on the right .

name = '+++Python New horizons +++'
name.rstrip('+')
 Copy code 
output:'+++Python New horizons '

3️⃣ strip() the truth is that lstrip() And rstrip() The combination of , It intercepts the characters specified on both sides of the string .

name = '+++Python New horizons +++'
name.strip('+')
 Copy code 
output:'Python New horizons '

str.split() & str.splitlines()

1️⃣ str.split(sep=None, maxsplit=-1) Use sep Split the string as a delimiter , Returns a list of words in a string .

  • seq: The separator used to split the string .None( The default value is ) Means to split according to any space , The returned result does not contain spaces .
  • maxsplit: Specify the maximum number of divisions .-1( The default value is ) Means unrestricted .
split_str = 'P y t h o n  new   Depending on the   wild '
split_str.split(maxsplit=2)
 Copy code 
output:['P', 'y', 't h o n new Depending on the wild ']

Use the default space for segmentation , Set the maximum number of divisions to 2


2️⃣ str.splitlines Returns a list of rows in a string , It follows the line ('\r',\n','\r\n') Separate , Returns a delimited list . It has only one parameter keepends Indicates whether to keep line breaks in the result ,False ( Default ) No reservation ,True Retain .

Example

split_str = 'P\ny\r t h o n  new   Depending on the   wild '
split_str.splitlines()
 Copy code 
output:['P', 'y', ' t h o n new Depending on the wild ']

Example

split_str = 'P\ny\r t h o n  new   Depending on the   wild '
split_str.splitlines(keepends=True)
 Copy code 
output:['P\n', 'y\r', ' t h o n new Depending on the wild ']

str.startswith() & str.endswith

1️⃣ startswith(prefix[, start[, end]]) Check if the string is to specify a substring substr start , yes True , no False, An empty string will report an error . If specified start and end , Check... Within the specified range .

startswith_str = 'Python New horizons '
startswith_str.startswith('thon', 2)
 Copy code 
output:True
From 3 Characters to start detection

2️⃣ str.endswith(suffix[, start[, end]]) And startswith The usage is the same , The difference is to check whether the string ends with the specified substring , yes True , no False, An empty string will report an error .

endswith_str = 'Python New horizons '
endswith_str.endswith('thon', 0, 6)
 Copy code 
output:True
From 1 Characters to start detection , To the first 7 End of characters ( It doesn't include 7 individual ), Note that the scope here is actually the same as string slicing , It's all front closed and back open .

str.title() & str.istitle()

1️⃣ title() Returns the initial capital of each word in a string .

title_str = 'python New horizons  python New horizons '.title()
title_str
 Copy code 
output:'Python New horizons Python New horizons '

2️⃣ istitle() Determine whether the string satisfies the initial capitalization of each word , yes True , no False, Empty string returns False.

'Abc Def '.istitle()
 Copy code 
output:True

str.upper() & str.isupper()

1️⃣ upper() Converts the letters in the specified string to uppercase .

upper_str = 'Python New horizons '.upper()
upper_str
 Copy code 
output:'PYTHON New horizons '

2️⃣ isupper() Determines whether all case sensitive characters in a string are capitalized , yes True , no False, An empty string or a string with no case sensitive characters returns False .

'PYTHON-SUN'.isupper()
 Copy code 
output:True

This is all the content of this article , If it feels good . Let's go with a compliment !!!


For beginners  Python  Or want to get started  Python  Little buddy , You can search through wechat 【Python New horizons 】, Exchange and study together , They all come from novices , Sometimes a simple question card takes a long time , But maybe someone else's advice will suddenly realize , I sincerely hope you can make progress together .

copyright notice
author[Dream, killer],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310121399886.html

Random recommended