程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning 1 (variables, statements, strings)

編輯:Python

python Programming specification PEP8
pycharm format ctrl + alt + l, You can see some commonly used shortcut keys here
Multiline comment ’‘’ The comment ‘’’

Variable declaration and type conversion

python Is a weak language , Variable declaration is not very strict with data types
Format : Variable name = value
python It is recommended that variable names be underlined
type() View data type
python It is more recommended to separate words with underscores in variable names : Variable name , Function names and file names are all lowercase , Use underscores to connect ; The class name follows the nomenclature of the great hump ; Constant names are all uppercase ;

For strings , Single quotation marks , Double quotes are OK , Three quotation marks can also ( After assignment symbol )
Why should there be three forms to represent strings
To distinguish between nested quotation marks
for example m = " sdfsdf’dfsdf’"

Three quotation marks are used to keep format for output :

python The type of input is string

# It's no problem to convert floating-point type directly to integer type , Numbers after the decimal point are ignored 
a = 9.9
print(int(a)) # 9
# If a string is converted into an integer, there will be a problem 
a = '9.9'
print(int(a)) # Report errors 
# String rotation float Sure 
a = '9.9'
print(float(a))
# True The conversion integer corresponds to 1,False yes 0
# True To floating point yes 1.0,False yes 0.0
# Boolean to string directly becomes a string 
# As long as it's not 0 Convert the number of to Boolean bool All are true
# Empty string to ('') Switch to bool yes False
print(bool(''))
print(bool(""))
print(bool(0))
print(bool({
}))
print(bool([]))
print(bool(()))
print(bool(None))
# All are false
# Specify the interval symbol in the output 
print(1,2,3,sep='#')
# Output results 
# 1#2#3

end Indicates what to add to the result

Operator

# Multiple variable assignments ( Separated by commas )
>>> num1, f1, str1 = 100, 3.14, "hello"
>>> num1
100
>>> f1
3.14
>>> str1
"hello"

Numbers and strings do == The result is false, except == When performing logical operations other than , Will report an error directly .
If you are comparing two strings , Each character will be converted to the corresponding encoding , Then compare them one by one .

print(80<=90<100) # True

Here we need to pay attention to , When there are many logical operators connected , You need to pay attention to which value is taken
Because when taking logic here , It is also short circuit and or short circuit or , So take the last valid value

a = 1
b = 3
print(a and b) # Output 3, Take the following value 
print(a or b) # Output 1, Take the previous value 
c = 0
print(c and a) # Output 0
a = 34
a > 10 and print('hello world') # Have output 
a < 10 and print('hello world') # There is no output 
a >10 or print(' Hello world ') # There is no output 
a <10 or print(' Hello world ') # Have output 

Format output

About formatting output , How many decimal places are reserved for output

money = 99.56
print(' I earned %f Yuan ' %money)
# out: I earned 99.560000 Yuan 
# You can see that there are many unnecessary zeros 
print(' I earned %.2f Yuan ' %money)
# Here will be rounded 
money = 99.55
print(' I earned %.1f Yuan ' %money)
# I earned 99.5 Yuan 
money = 99.56
print(' I earned %.1f Yuan ' %money)
# I earned 99.6 Yuan 

Hexadecimal conversion

bin(),oct(),hex()
0b,0o,0x

# Binary conversion 
n = 149
r = bin(n)
print(r) # 0b10010101
# turn 8 Base number 
r = oct(n)
print(r) # 0o225
# turn 16 Base number 
r = hex(n)
print(r) # 0x95
# The default output is decimal 
n = 0x558
print(oct(n)) # 0o2530
# Or use int transformation 
r = int(n) # 1368

An operation

Here we need to pay attention to the left shift will not overflow , Will always get bigger

Operator priority

Conditional statements

random.randint(1, 10) produce 1 To 10 The random number (1 and 10 Both contain )

pass keyword To support the structure , such as if If the condition is written but the content is not written, an error will be reported , A structure called collapse , Write a pass Can support this structure , Don't make a mistake

stay Python Allow similar to 5<a<10 Writing
stay Python in , When converted to Boolean , Only 0,“”,‘’,None,(),{},[] Will be converted into False, Everything else will be transformed into True
Ternary operator

a = 10
b = 30
c = a if a>b else b

amount to

a = 10
b = 30
if a > b:
c = a
else:
c = b

Loop statement

while / for
stay Python in for Loop can traverse any sequence of items , Such as a list or a string .
for Circular format :

for Temporary variable in Iteratable objects such as lists or strings :
Code executed when the loop meets the conditions

range Can generate numbers for for Loop traversal , It can pass three parameters , respectively start 、 End and step .
Include starting position , Do not include the ending value
The default is 0 At the beginning , The default step size is 1

>>> range(2, 10, 3)
[2, 5, 8]
>>> for x in range(2, 10, 3):
... print(x)
...
2
5
8

stay Python in ,break and continue Can only be used in loop statements .
break and continue When used in nested loops , Only valid for innermost loop .

stay Python in , Circular statements can also be used with else Statements are used in conjunction with

while Judge the condition :
When conditions are met , Loop body code
else:
If the loop has not been interrupted , To be executed ; If it jumps out during execution , Then this will not be implemented

From the above structure , We can see that , In a non dead cycle , Under normal circumstances else All the statements in the will be executed . So this one else What is the function of statements ? In general , Loop statements and else When they appear together , In circular statements, it will cooperate break Statement to use .

Escape character

\r It means returning to the beginning of this line , Print the following

print("abcd\r efg")
-----
print("abcd\n efg")
Output :
efg
-----
abcd
efg

character string

Get address function id()
is The operator compares addresses
As can be seen from the following example , The same string shares memory , amount to java String constant pool in

s1 = 'hello'
s2 = s1
s3 = 'hello'
print(id(s1))
print(id(s2))
print(id(s3))
print(s1 is s2)
s1 = 'word'
print(s1, s2, s3)
Output :
2035658937544
2035658937544
2035658937544
True
word hello hello

The string index can be from front to back , from 0 Start to len(s) - 1
You can go back and forth , from -len(s) Start to -1

section

Slicing refers to the operation of intercepting part of the operation object . character string 、 list 、 Tuples all support slicing .

The syntax of slicing :[ start : end : step ], It can also simplify the use of [ start : end ]

Be careful : The selected interval is from " start " Bit start , To " end " The last one of the first ( Does not include the end bit itself ), The step size represents the selection interval , You can also control the direction , A negative number means taking... From right to left .

find,rfind,index,rindex

find Finds whether the specified content exists in the string , If it exists, it returns the index value of the start position of the content for the first time in the string , If it doesn't exist , Then return to -1.

Grammar format :([] Is the content that can be added )
S.find(sub[, start[, end]]) -> int
end Also not included

mystr = ' It's a fine day today , Beautiful scenery everywhere '
id_f = mystr.find(' wind ') # 11
print(mystr.find(' Good scenery ')) # 10 ' Good scenery ' When it first appeared ,' good ' Where it is 
print(mystr.find(' Hello ')) # -1 ' Hello ' non-existent , return -1
print(mystr.find(' wind ', 12)) # 15 From the subscript 12 Start looking for ' wind ', Find where the wind is and try 15
print(mystr.find(' wind ', 11)) # 11 From the subscript 12 Start looking for ' wind ', Find where the wind is and try 11
print(mystr.find(' wind ',0,id_f)) # -1 From the subscript 0 Start to 10 lookup " wind ", Not found , return -1

rfind It's from right to left

index Follow find() The method is the same , It's just ,find Method not found , return -1, and str When not found , An exception will be reported .

startwith、endswith

startswith Determines whether the string starts with the specified content . Grammar format :

S.startswith(prefix[, start[, end]]) -> bool

isalpha、isdigit、isalnum、isspace

isalpha Determine whether the string is a pure letter .
isdigit Determine whether a string is a pure number , As long as there is something wrong 0~9 The number of , The result is False.
isalnum Decide if it's made up of numbers and letters . As long as there are non numbers and letters , Just go back to False.
isspace If mystr Contains only Spaces , Then return to True, Otherwise return to False.
isupper Judge whether all the letters in the string are capital letters
islower Judge whether all the letters in the string are lowercase , as follows

s = "123dddd"
print(s.islower()) # True

count

return str stay start and end Between stay mystr The number of times it's inside .

Grammar format :
S.count(sub[, start[, end]]) -> int

replace

Replace what is specified in the string , If you specify the number of times count, Then the replacement will not exceed count Time .
replace(old, new, count)

mystr = ' It's a fine day today , Beautiful scenery everywhere '
newstr = mystr.replace(' good ', ' bad ')
print(mystr) # It's a fine day today , Beautiful scenery everywhere The original string has not changed !
print(newstr) # The weather is bad and sunny today , Everywhere bad scenery, bad scenery In the new string obtained ,' good ' It was modified to ' bad '
newstr = mystr.replace(' good ',' bad ',2) # Specifies the number of replacements 
print(newstr) # The weather is bad and sunny today , Bad scenery everywhere, good scenery There are only two ' good ' Replaced with ' bad '

If you replace two words at a time , Can pass 1. Regular expressions to handle 2. loop + list

Division split

Content separation mainly involves split,rsplit, splitlines,partition and rpartition Four ways .

split(‘ Separator ’, maxsplit) The result is a list , cut maxsplit The knife

splitlines Separate by lines , Returns a list of rows as elements .

partition hold mystr With str Divided into three parts ,str front ,str and str after , Three parts make up a tuple

mystr = ' It's a fine day today , Beautiful scenery everywhere '
print(mystr.partition(' good ')) # (' The weather today ', ' good ', ' sunny , Beautiful scenery everywhere ')

toggle case

The function of changing case is only valid for English , It mainly includes , title case capitalize, Capitalize each word title, Full lowercase lower, All capitals upper.

A space , Align left align right align Center

What is commonly used is strip, Remove the space on the left and right

ljust Returns a string of a specified length , And use blank characters on the right to complete ( Align left ).

str = 'hello'
print(str.ljust(10)) # hello Fill in five blanks on the right 

rjust Returns a string of a specified length , And use blank characters on the left to complete ( Right alignment ).

str = 'hello'
print(str.rjust(10)) # hello Fill in five blanks on the left 

center Returns a string of a specified length , And use blank characters at both ends to complete ( Align center )

str = 'hello'
print(str.center(10)) # hello Space at both ends , Center the content 

lstrip Delete mystr The white space on the left .

mystr = ' he llo '
print(str.lstrip()) #he llo Only the space on the left is removed , The middle and right spaces are reserved 

rstrip Delete mystr The white space on the right .

mystr = ' he llo '
print(str.rstrip()) # he llo The space on the right is deleted 

strip Delete the broken white space characters .

str = ' he llo '
print(str.strip()) #he llo

String splicing

Traverse the parameters , Take out each item in the parameter , Then add mystr

Grammar format :
S.join(iterable)

Example :

mystr = 'a'
print(mystr.join('hxmdq')) #haxamadaq hold hxmd Take them out one by one , And add characters after a. final q Retain , No addition a
print(mystr.join(['hi','hello','good'])) #hiahelloagood

effect : You can quickly convert a list or tuple into a string , And separated by the specified characters .

txt = '_'
print(txt.join(['hi','hello','good'])) #hi_hello_good
print(txt.join(('good','hi','hello'))) #good_hi_hello

String operators

  1. The addition operator can be used between strings , The function is to splice two strings into one string . for example :‘hello’ + 'world’ The result is ‘helloworld’
  2. You can multiply between strings and numbers , The result is to repeat the specified string multiple times . for example :‘hello’*2 The result is hellohello
  3. Between strings , If the comparison operator is used for calculation , The encoding corresponding to the character will be obtained , And then compare them .
  4. In addition to the above operators , String does not support other operators by default .

String formatting format

  1. str.format() Method through braces in the string {} To identify replacement fields replacement field, To complete the format of the string .
  2. Replace fields By field name field name And transform fields conversion field And the format specifier format specifier form , The general form is { Field name ! Convert fields : Format specifier }.
  3. Field names are divided into simple field names simple field name And compound field names compound field name. The conversion field and format specifier are optional .

Simple field name

Simple field names are written in three ways :

Omit the field name :{}
Use nonnegative decimal integers {0}
Variable name {name}

Omit the field name

Omit the field name in braces , Passing positional parameters .
Replace field form : {}
Be careful : The number of braces can be less than the number of positional parameters , Otherwise .

# Omit the field name and pass the location parameter 
print(' My name is {}, This year, {} year .'.format(' Xiao Ming ', 18))
""" My name is Xiao Ming , This year, 18 year . """
# The number of braces can be less than the number of positional parameters 
print(' I love to eat {} and {}.'.format(' Banana ', ' Apple ', ' Daya pear '))
""" I like bananas and apples . """
# If the number of braces is more than the number of positional parameters, an error will be reported 
# print(' I still eat {} and {}.'.format(' tomatoes '))
""" IndexError: tuple index out of range """
Numeric field name

Positional parameters can be passed through simple field names in numeric form .

The number must be greater than or equal to 0 The integer of .
Replacement fields with numbers can be reused .
A simple field name in numeric form is equivalent to format All positional parameters in are treated as a tuple as a whole , The value is obtained by the number in the field name . namely {0} Equivalent to tuple[0], So the numbers in braces can't cross the line .

# Pass positional parameters through simple field names in numeric form 
print(' height {0}, Live at home {1}.'.format(1.8, ' Causeway Bay '))
""" height 1.8, I live in Causeway Bay """
# Simple field names in numeric form can be reused .
print(' I love {0}.\n She is {1}.\n I also love {0}.'.format(' Asarum ', 17))
""" I love ah Xiang . She is 17. I also love ah Xiang . """
# Experience taking all position parameters as a whole as tuples 
print(' Ah Xiang likes to eat {1}、{3} and {0}.'.format(
' durian ', ' Stinky tofu ', ' Preserved egg ', ' Canned herring ', ' Snail lion powder '))
""" Ah Xiang likes stinky tofu 、 Canned herring and durian . """
# Try the cross-border error 
# print('{1}'.format(' Incorrect usage '))
""" IndexError: tuple index out of range """
Variable field name

Pass keyword parameters using simple field names in the form of variable names .

The position of keyword parameters can be changed at will .

# Pass keyword parameters using simple field names in the form of variable names 
print(' My eldest brother is {name}, This year, {age} year .'.format(name=' A fly ', age=20))
""" My eldest brother is ah Fei , This year, 20 year . """
# The order of keyword parameters can be changed at will 
print(' My eldest brother is {name}, This year, {age} year .'.format(age=20, name=' A fly '))
""" My eldest brother is ah Fei , This year, 20 year . """
Mixed use of simple field names

Use a mixture of field names in the form of numbers and variable names , You can pass location parameters and keyword parameters at the same time .
The keyword parameter must be after the positional parameter .
Numbers can be omitted when mixed .
Omit the field name {} Field names in numeric form cannot be { Non-negative integer } Use at the same time .

# Use a mixture of field names in the form of numbers and variable names 
# You can pass location parameters and keyword parameters at the same time 
print(' This is one about {0}、{1} and {girl} The story of .'.format(
' Xiao Ming ', ' A fly ', girl=' Asarum '))
""" This is a story about Xiao Ming 、 The story of ah Fei and Ah Xiang . """
# But the keyword parameter must be after the positional parameter 
# print(' This is one about {0}、{1} and {girl} The story of .'.format(
# ' Xiao Ming ', girl=' Asarum ' , ' A fly '))
""" SyntaxError: positional argument follows keyword argument """
# Numbers can also be omitted 
print(' This is one about {}、{} and {girl} The story of .'.format(
' Xiao Ming ', ' A fly ', girl=' Asarum '))
# However, omitting field names cannot occur at the same time as field names in numeric form 
# print(' This is one about {}、{1} and {girl} The story of .'.format(
# ' Xiao Ming ', ' A fly ', girl=' Asarum '))
""" ValueError: cannot switch from automatic field numbering to manual field specification """
2.1.5 Use tuples and dictionaries to pass parameters

str.format() The method can also be used * Tuples and ** Dictionaries In the form of biography , The two can be mixed . Positional arguments 、 Key parameters 、* Tuples and ** Dictionaries It can also be used at the same time , But be careful , Position parameter should be in front of keyword parameter ,* Tuples To be in ** Dictionaries front .

# Use tuples to pass parameters 
infos = ' Iron man ', 66, ' Pepper '
print(' I am a {}, worth {} Billion .'.format(*infos))
""" I'm iron man , oneself and one's family 66 Billion . """
print(' I am a {2}, worth {1} Billion .'.format(*infos))
""" I'm pepper , oneself and one's family 66 Billion . """
# Use a dictionary to pass references 
venom = {
'name': ' venom ', 'weakness': ' fire '}
print(' I am a {name}, I'm afraid {weakness}.'.format(**venom))
""" I am venom , I'm afraid of fire . """
# Use both tuples and dictionaries to pass parameters 
hulk = ' The Incredible Hulk ', ' fist '
captain = {
'name': ' Captain America ', 'weapon': ' shield '}
print(' I am a {}, I'm afraid {weapon}.'.format(*hulk, **captain))
print(' I am a {name}, I'm afraid {1}.'.format(*hulk, **captain))
""" I'm Hulk , I'm afraid of shield . I'm Captain America , I'm afraid of fists . """
# Use position parameters at the same time 、 Tuples 、 Key parameters 、 Dictionary reference 
# Be careful :
# Position parameter should be in front of keyword parameter 
# * Tuples should be in ** In front of the dictionary 
tup = ' Eagle eye ',
dic = {
'weapon': ' arrow '}
text = ' I am a {1}, I'm afraid {weakness}. I am a {0}, I use {weapon}.'
text = text.format(
*tup, ' Black widow ', weakness=' Man ', **dic)
print(text)
""" I'm the black widow , I'm afraid of men . I'm eagle eye , I use an arrow . """

Compound field name

Field names that use both numeric and variable names are compound field names .
Two operators are supported for compound field names :

. Order number
[] brackets

Use . Order number

Passing positional parameters
Replace field form :{ Numbers . Property name }
When there is only one replacement field, the number can be omitted

class Person(object):
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
p = Person('zhangsan',18,'female')
print(' Name is {0.name}, Age is {0.age}, Gender is {0.gender}'.format(p))
print(' Name is {.name}'.format(p)) # When there is only one replacement field , Numbers can be omitted 
Use [] brackets

Pass positional parameters in a list
Pass positional parameters with tuples
Pass location parameters with dictionary

# Use of brackets : Pass positional parameters in a list 
infos = [' star ', 9527]
food = [' Overlord flower ', ' popcorn ']
print(' My name is {0[0]}, Police signal {0[1]}, Love eating {1[0]}.'.format(
infos, food))
""" My name is a Xing , Police signal 9527, Love to eat overlord flowers . """
# Use of brackets : Pass positional parameters with tuples 
food = (' Corpse ', ' mind ')
print(' My name is {0[0]}, Age {1}, Love eating {0[1]}.'.format(
food, 66))
""" My name is Zombie , Age 66, Love to eat brain . """
# Use of brackets : Pass location parameters with dictionary 
dic = dict(name=' star ', pid=9527)
print(' I am a {[name]}!'.format(
dic))
# Multiple replacement fields , The number... Cannot be omitted 
print(' I am a {0[name]}, Police signal {0[pid]}.'.format(
dic))
""" I'm a Xing ! I'm a Xing , Police signal 9527. """

Convert fields

Convert fields conversion field There are three values of , Add in front. !:

s: Call... On the parameter before passing it str()
r: Call... On the parameter before passing it repr()
a: Call... On the parameter before passing it ascii()

ascii() Function similar to repr() function , Returns a string that can represent an object . But for non ASCII character , Use \x,\u perhaps \U escape .

# Convert fields 
print('I am {!s}!'.format('Bruce Lee Bruce Lee '))
print('I am {!r}!'.format('Bruce Lee Bruce Lee '))
print('I am {!a}!'.format('Bruce Lee Bruce Lee '))
""" I am Bruce Lee Bruce Lee ! I am 'Bruce Lee Bruce Lee '! I am 'Bruce Lee \u674e\u5c0f\u9f99'! """

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved