admin 發表於 2023-4-23 15:45:45

The Python Tutorial

The Python Tutorial — Python 3.11.3 documentation

1)Source Code Encoding:By default, Python source files are treated as encoded in UTF-8.
To declare an encoding other than the default one, a special comment line should be added as the first line of the file. The syntax is as follows
# -*- coding: encoding -*-where encoding is one of the valid codecs supported by Python.
# -*- coding: cp950 -*-cp950 950, ms950 Traditional Chinese

2)Argument Passing 函數的可變參數 In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols:
[*]*args (Non Keyword Arguments)
[*]**kwargs (Keyword Arguments)
*args是可變的positional arguments列表,**kwargs是可變的keyword arguments列表。兩個可以同時使用,但在使用時,*args必須在**kwargs的前面,因為positional arguments,有位置順序的對應,必須位於keyword arguments之前。
def fun(a, *args, **kwargs):
    print("a={}".format(a))
    for arg in args:
      print('Optional argument: {}'.format( arg ) )

    for k, v in kwargs.items():
      print('Optional kwargs argument key: {} value {}'.format(k, v))

執行結果為
a=1
Optional argument: 22
Optional argument: 33
Optional kwargs argument key: k1 value 44
Optional kwargs argument key: k2 value 55</span>
In interactive mode, the last printed expression is assigned to the variable
tax = 12.5 / 100
price = 100.50
price * tax
12.5625
price + _
113.0625
round(_, 2)
113.06

StringsThey can be enclosed in single quotes ('...') or double quotes ("...") with the same result. \ can be used to escape quotes:
In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes.
>>>'spam eggs'# single quotes
'spam eggs'
>>>'doesn\'t'# use \' to escape the single quote...
"doesn't"
>>>"doesn't"# ...or use double quotes instead
"doesn't"
>>>'"Yes," they said.'
'"Yes," they said.'
>>>"\"Yes,\" they said."
'"Yes," they said.'
>>>'"Isn\'t," they said.'
'"Isn\'t," they said.'
>>>'"Isn\'t," they said.'
'"Isn\'t," they said.'
>>>print('"Isn\'t," they said.')
"Isn't," they said.
>>>s = 'First line.\nSecond line.'# \n means newline
>>>s# without print(), \n is included in the output
'First line.\nSecond line.'
>>>print(s)# with print(), \n produces a new line
First line.
Second line
If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:
>>>print('C:\some\name')# here \n means newline!
C:\some
ame
>>>print(r'C:\some\name')# note the r before the quote
C:\some\name


String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line.
print("""\
Usage: thingy
   -h                        Display this usage message
   -H hostname               Hostname to connect to
""")
produces the following output (note that the initial newline is not included):

Usage: thingy
   -h                        Display this usage message
   -H hostname               Hostname to connect to
Strings can be concatenated (glued together) with the + operator, and repeated with *:
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.
If you want to concatenate variables or a variable and a literal, use +:


Strings can be indexed (subscripted), with the first character having index 0.
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s is always equal to s:


>>>word[-1]# last character
'n'
>>>word[-2]# second-last character
'o'
>>>word[-6]


>>>word# characters from position 0 (included) to 2 (excluded)
'Py'
>>>word# characters from position 2 (included) to 5 (excluded)
'tho'
>>>word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>>word   # characters from position 4 (included) to the end
'on'
>>>word[-2:]# characters from the second-last (included) to the end
'on'
>>>word[:2] + word
'Python'
>>>word[:4] + word
'Python'

The built-in function len() returns the length of a string:



頁: [1]
查看完整版本: The Python Tutorial