1.查看一个库里面有什么函数方法可以通过以下
import math
print(dir(math))
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
2.format函数
- 例一
planet = 'Pluto'
position = 9
"{}, you'll always be the {}th planet to me.".format(planet, position)
用format做字符串拼接不用将int先转为str,format会自动转变他
"Pluto, you'll always be the 9th planet to me."
- 例二
pluto_mass = 1.303 * 10**22
earth_mass = 5.9722 * 10**24
population = 52910390
"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format(
planet, pluto_mass, pluto_mass / earth_mass, population,
)
###2 decimal points 3 decimal points, format as percent separate with commas
"Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians."
- 例三
Referring to format() arguments by index, starting from 0
s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format('planet', 'dwarf planet')
print(s)
Pluto's a planet.
No, it's a dwarf planet.
planet!
dwarf planet!
3.List functions
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
- len gives the length of a list:
len(planets)
8
- sorted returns a sorted version of a list:
sorted(planets)
['Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus']
- sum does what you might expect:
primes = [2, 3, 5, 7]
sum(primes)
17
- min and max
max(primes)
7
4.List methods
- list.append modifies a list by adding an item to the end:
planets.append('Pluto')
- list.pop removes and returns the last element of a list:
planets.pop()
'Pluto'
- Searching lists,using the list.index method
planets.index('Earth')
2
查找一个list中最小值的索引值
list_a.index(min(list_a))
5.String methods
Like list, the type str has lots of very useful methods. I’ll show just a few examples here.
- str.upper()与str.lower()
claim = "Pluto is a planet!"
claim.upper()
'PLUTO IS A PLANET!'
claim.lower()
'pluto is a planet!'
- .split() 与 .join()
str.split() turns a string into a list of smaller strings, breaking on whitespace by default. This is super useful for taking you from one big string to a list of words.
words = claim.split()
words
['Pluto', 'is', 'a', 'planet!']
Occasionally you’ll want to split on something other than whitespace:
datestr = '1956-01-31'
year, month, day = datestr.split('-')
str.join() takes us in the other direction, sewing a list of strings up into one long string, using the string it was called on as a separator.
'/'.join([month, day, year])
'01/31/1956'
' 👏 '.join([word.upper() for word in words])
'PLUTO 👏 IS 👏 A 👏 PLANET!'