Python----基础之数据类型(数字,字符串,列表)

什么是基本数据类型?

我们人类可以很容易的分清数字与字符的区别,但是计算机并不能呀,计算机虽然很强大,但从某种角度上看又很傻,除非你明确的告诉它,1是数字,“汉”是文字,否则它是分不清1和‘汉’的区别的,因此,在每个编程语言里都会有一个叫数据类型的东东,其实就是对常用的各种数据类型进行了明确的划分,你想让计算机进行数值运算,你就传数字给它,你想让他处理文字,就传字符串类型给他。

数字

int

在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

long

跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。

注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。

>>> a= 2**64
>>> type(a)  #type()是查看数据类型的方法
<type 'long'>
>>> b = 2**60
>>> type(b)
<type 'int'>
View Code

注意:在python3里不再有long类型,全部都是int

整型

Python中的整数属于int类型,默认用十进制表示,此外也支持二进制,八进制,十六进制表示方式。

进制转换:

尽管计算机只认识二进制,但是为了迎合我们的习惯,python中的数字默认还是十进制。还提供了一些方法来帮助我们做转换。比如是十进制转换为二进制使用bin方法,在转换结果前面还会加上‘0b’表示是一个二进制数。

既然十进制可以转换为二进制,那么其实使用同样的原理也可以转换为其他进制,python也为我们提供了十进制转换成八进制和十六进制的方法,分别是oct和hex。八进制前面以‘0o’标示,十六进制以‘0x’标示。

>>> bin(10)  # bin方法是十进制转换二进制,‘0b’标示为二进制
'0b1010'
>>> oct(10)  # oct方法是十进制转换为八进制,‘0o’标示为八进制
'0o12'
>>> hex(10)  # hex方法是十进制转换为十六进制‘0x’标示为十六进制
'0xa'

取余运算(%)

>>> 7 % 5  
2
>>> 5 % 2
1
>>> 16 % 4
0

算术运算(+  -  *  /  //  divmod  **)

>>> 2+3
5
>>> 2-3
-1
>>> 2*3
6
>>> 3/2
1.5
>>> 3//2
1
>>> divmod(16,3)
(5, 1)
>>> 2**3
8

浮点型

浮点数是属于有理数中某特定子集的数的数字表示,在计算机中用以近似表示任意某个实数。具体的说,这个实数由一个整数或定点数(即尾数)乘以某个基数(计算机中通常是2)的整数次幂得到,这种表示方法类似于基数为10的科学计数法。

为什么要叫做float浮点型?

在运算中,整数与浮点数运算的结果也是一个浮点数。

1 浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,
2 一个浮点数的小数点位置是可变的,比如,
3 1.23*109和12.3*108是相等的。
4 浮点数可以用数学写法,如1.23,3.14,-9.01,等等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代:
5 1.23*109就是1.23e9,或者12.3e8,0.000012可以写成1.2e-5,等等。
6 整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的而浮点数运算则可能会有四舍五入的误差。

关于小数不精准问题

 Python默认的是17位精度,也就是小数点后16位,尽管有16位,但是这个精确度却是越往后越不准的。 首先,这个问题不是只存在在python中,其他语言也有同样的问题 其次,小数不精准是因为在转换成二进制的过程中会出现无限循环的情况,在约省的时候就会出现偏差。 

这里有一个问题,就是当我们的计算需要使用更高的精度(超过16位小数)的时候该怎么做呢?

#借助decimal模块的“getcontext“和“Decimal“ 方法
>>> a = 3.141592653513651054608317828332
>>> a
3.141592653513651
>>> from decimal import *
>>> getcontext()
Context(prec=50, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow])
>>> getcontext().prec = 50
>>> a = Decimal(1)/Decimal(3)#注,在分数计算中结果正确,如果直接定义超长精度小数会不准确
>>> a
Decimal('0.33333333333333333333333333333333333333333333333333')

>>> a = '3.141592653513651054608317828332'
>>> Decimal(a)
Decimal('3.141592653513651054608317828332')

字符串

在python中,加了引号的都被认为是字符串!

 1 >>> str = 'test1'
 2 >>> str
 3 'test1'
 4 >>> print(type(str))
 5 <class 'str'>
 6 >>> str1 = '123'
 7 >>> str1
 8 '123'
 9 >>> print(type(str1))
10 <class 'str'>
11 >>> str2 = "test3"
12 >>> str2
13 'test3'
14 >>> print(type(str2))
15 <class 'str'>
View Code

单双引号没有任何区别,只有在下面这种情况需要单双引号的配合:

1 >>> test = "I'm 18 years old"
2 >>> test
3 "I'm 18 years old"
View Code

在字符串中有单引号的时候,字符串外边要用双引号。

多引号的作用,就是多行字符串必须用字符串

msg = """
    1.打印第一行
    2.打印第二行
    3.打印第三行
"""
print(msg)
View Code

字符串拼接

>>> name = 'ike'
>>> age = '22'
>>> name + age
'ike 22'
>>> name * 5
'ikeikeikeikeike'
View Code

字符串之间可以相加,字符串可以乘法运算。

注意!字符串之间拼接,必须类型都是字符串,如果不一致会报TypeError错误

字符串的定义与创建

字符串是一个有序的字符的集合,用于存储和表示基本的文本信息

hello = "hello! everyone"'

字符串的特性与常用操作

特性:

1.按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序:

补充:

1.字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如name=r'l\thf'

2.unicode字符串与r连用必需在r前面,如name=ur'l\thf'

常用操作:

 1 # 索引取值
 2 >>> we = 'happy'
 3 >>> we[0]  
 4 'h'
 5 >>> we[-1]
 6 'y'
 7 >>>
 8 >>>
 9 # 使用index方法取索引的指
10 >>> we.index('y')
11 4
1 # 使用find方法查询
2 >>> we.index('y')
3 4
4 >>> we.find('a')
5 1
6 >>> we.find('y')
7 4
8 >>> we.find('w')
9 -1
 1 # 去除空白
 2 >>> we = '   happy   '
 3 >>> we
 4 '   happy   '
 5 >>> we.strip()
 6 'happy'
 7 >>> we
 8 '   happy   '
 9 >>> we.rstrip()
10 '   happy'
11 >>> we.lstrip()
12 'happy   '
13 >>>
1 # len方法查长度
2 >>> we = 'happy'
3 >>> len(we)
4 5
# replace方法替换
>>> we = 'happy'
>>> we
'happy'
>>> we.replace('h', 'H')
'Happy'
>>> we1 = 'happy haha'
>>> we1.replace('h', 'H')
'Happy HaHa'
# 切片用法
>>> we = 'abcdefghigklmn'
>>> we[0:6]  # 从第一个到第六个
'abcdef'
>>> we[5:8]  # 从第6个到第八个
'fgh'
>>> we[:9]  # 从第一个到第9个
'abcdefghi'
>>> we[4:]  # 从第5个到最后
'efghigklmn'
>>> we[:]  # 从第一个到最后
'abcdefghigklmn'
>>> we[0:8:2]  # 从第一个到第8个,中间跳一个
'aceg'
>>> we[::2]  # 从第一个到最后一个,中间跳一个
'acegikm'
>>> we[::-1]  # 从第一个到最后一个,倒着排
'nmlkgihgfedcba 

字符串的工厂函数

  1 class str(object):
  2     """
  3     str(object='') -> str
  4     str(bytes_or_buffer[, encoding[, errors]]) -> str
  5 
  6     Create a new string object from the given object. If encoding or
  7     errors is specified, then the object must expose a data buffer
  8     that will be decoded using the given encoding and error handler.
  9     Otherwise, returns the result of object.__str__() (if defined)
 10     or repr(object).
 11     encoding defaults to sys.getdefaultencoding().
 12     errors defaults to 'strict'.
 13     """
 14     def capitalize(self): # real signature unknown; restored from __doc__
 15         """
 16         首字母变大写
 17         S.capitalize() -> str
 18 
 19         Return a capitalized version of S, i.e. make the first character
 20         have upper case and the rest lower case.
 21         """
 22         return ""
 23 
 24     def casefold(self): # real signature unknown; restored from __doc__
 25         """
 26         S.casefold() -> str
 27 
 28         Return a version of S suitable for caseless comparisons.
 29         """
 30         return ""
 31 
 32     def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
 33         """
 34         原来字符居中,不够用空格补全
 35         S.center(width[, fillchar]) -> str
 36 
 37         Return S centered in a string of length width. Padding is
 38         done using the specified fill character (default is a space)
 39         """
 40         return ""
 41 
 42     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 43         """
 44          从一个范围内的统计某str出现次数
 45         S.count(sub[, start[, end]]) -> int
 46 
 47         Return the number of non-overlapping occurrences of substring sub in
 48         string S[start:end].  Optional arguments start and end are
 49         interpreted as in slice notation.
 50         """
 51         return 0
 52 
 53     def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
 54         """
 55         encode(encoding='utf-8',errors='strict')
 56         以encoding指定编码格式编码,如果出错默认报一个ValueError,除非errors指定的是
 57         ignore或replace
 58 
 59         S.encode(encoding='utf-8', errors='strict') -> bytes
 60 
 61         Encode S using the codec registered for encoding. Default encoding
 62         is 'utf-8'. errors may be given to set a different error
 63         handling scheme. Default is 'strict' meaning that encoding errors raise
 64         a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 65         'xmlcharrefreplace' as well as any other name registered with
 66         codecs.register_error that can handle UnicodeEncodeErrors.
 67         """
 68         return b""
 69 
 70     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
 71         """
 72         S.endswith(suffix[, start[, end]]) -> bool
 73 
 74         Return True if S ends with the specified suffix, False otherwise.
 75         With optional start, test S beginning at that position.
 76         With optional end, stop comparing S at that position.
 77         suffix can also be a tuple of strings to try.
 78         """
 79         return False
 80 
 81     def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
 82         """
 83         将字符串中包含的\t转换成tabsize个空格
 84         S.expandtabs(tabsize=8) -> str
 85 
 86         Return a copy of S where all tab characters are expanded using spaces.
 87         If tabsize is not given, a tab size of 8 characters is assumed.
 88         """
 89         return ""
 90 
 91     def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 92         """
 93         S.find(sub[, start[, end]]) -> int
 94 
 95         Return the lowest index in S where substring sub is found,
 96         such that sub is contained within S[start:end].  Optional
 97         arguments start and end are interpreted as in slice notation.
 98 
 99         Return -1 on failure.
100         """
101         return 0
102 
103     def format(self, *args, **kwargs): # known special case of str.format
104         """
105         格式化输出
106         三种形式:
107         形式一.
108         >>> print('{0}{1}{0}'.format('a','b'))
109         aba
110 
111         形式二:(必须一一对应)
112         >>> print('{}{}{}'.format('a','b'))
113         Traceback (most recent call last):
114           File "<input>", line 1, in <module>
115         IndexError: tuple index out of range
116         >>> print('{}{}'.format('a','b'))
117         ab
118 
119         形式三:
120         >>> print('{name} {age}'.format(age=12,name='lhf'))
121         lhf 12
122 
123         S.format(*args, **kwargs) -> str
124 
125         Return a formatted version of S, using substitutions from args and kwargs.
126         The substitutions are identified by braces ('{' and '}').
127         """
128         pass
129 
130     def format_map(self, mapping): # real signature unknown; restored from __doc__
131         """
132         与format区别
133         '{name}'.format(**dict(name='alex'))
134         '{name}'.format_map(dict(name='alex'))
135 
136         S.format_map(mapping) -> str
137 
138         Return a formatted version of S, using substitutions from mapping.
139         The substitutions are identified by braces ('{' and '}').
140         """
141         return ""
142 
143     def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
144         """
145         S.index(sub[, start[, end]]) -> int
146 
147         Like S.find() but raise ValueError when the substring is not found.
148         """
149         return 0
150 
151     def isalnum(self): # real signature unknown; restored from __doc__
152         """
153         至少一个字符,且都是字母或数字才返回True
154 
155         S.isalnum() -> bool
156 
157         Return True if all characters in S are alphanumeric
158         and there is at least one character in S, False otherwise.
159         """
160         return False
161 
162     def isalpha(self): # real signature unknown; restored from __doc__
163         """
164         至少一个字符,且都是字母才返回True
165         S.isalpha() -> bool
166 
167         Return True if all characters in S are alphabetic
168         and there is at least one character in S, False otherwise.
169         """
170         return False
171 
172     def isdecimal(self): # real signature unknown; restored from __doc__
173         """
174         S.isdecimal() -> bool
175 
176         Return True if there are only decimal characters in S,
177         False otherwise.
178         """
179         return False
180 
181     def isdigit(self): # real signature unknown; restored from __doc__
182         """
183         S.isdigit() -> bool
184 
185         Return True if all characters in S are digits
186         and there is at least one character in S, False otherwise.
187         """
188         return False
189 
190     def isidentifier(self): # real signature unknown; restored from __doc__
191         """
192         字符串为关键字返回True
193 
194         S.isidentifier() -> bool
195 
196         Return True if S is a valid identifier according
197         to the language definition.
198 
199         Use keyword.iskeyword() to test for reserved identifiers
200         such as "def" and "class".
201         """
202         return False
203 
204     def islower(self): # real signature unknown; restored from __doc__
205         """
206         至少一个字符,且都是小写字母才返回True
207         S.islower() -> bool
208 
209         Return True if all cased characters in S are lowercase and there is
210         at least one cased character in S, False otherwise.
211         """
212         return False
213 
214     def isnumeric(self): # real signature unknown; restored from __doc__
215         """
216         S.isnumeric() -> bool
217 
218         Return True if there are only numeric characters in S,
219         False otherwise.
220         """
221         return False
222 
223     def isprintable(self): # real signature unknown; restored from __doc__
224         """
225         S.isprintable() -> bool
226 
227         Return True if all characters in S are considered
228         printable in repr() or S is empty, False otherwise.
229         """
230         return False
231 
232     def isspace(self): # real signature unknown; restored from __doc__
233         """
234         至少一个字符,且都是空格才返回True
235         S.isspace() -> bool
236 
237         Return True if all characters in S are whitespace
238         and there is at least one character in S, False otherwise.
239         """
240         return False
241 
242     def istitle(self): # real signature unknown; restored from __doc__
243         """
244         >>> a='Hello'
245         >>> a.istitle()
246         True
247         >>> a='HellP'
248         >>> a.istitle()
249         False
250 
251         S.istitle() -> bool
252 
253         Return True if S is a titlecased string and there is at least one
254         character in S, i.e. upper- and titlecase characters may only
255         follow uncased characters and lowercase characters only cased ones.
256         Return False otherwise.
257         """
258         return False
259 
260     def isupper(self): # real signature unknown; restored from __doc__
261         """
262         S.isupper() -> bool
263 
264         Return True if all cased characters in S are uppercase and there is
265         at least one cased character in S, False otherwise.
266         """
267         return False
268 
269     def join(self, iterable): # real signature unknown; restored from __doc__
270         """
271         #对序列进行操作(分别使用' '与':'作为分隔符)
272         >>> seq1 = ['hello','good','boy','doiido']
273         >>> print ' '.join(seq1)
274         hello good boy doiido
275         >>> print ':'.join(seq1)
276         hello:good:boy:doiido
277 
278 
279         #对字符串进行操作
280 
281         >>> seq2 = "hello good boy doiido"
282         >>> print ':'.join(seq2)
283         h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
284 
285 
286         #对元组进行操作
287 
288         >>> seq3 = ('hello','good','boy','doiido')
289         >>> print ':'.join(seq3)
290         hello:good:boy:doiido
291 
292 
293         #对字典进行操作
294 
295         >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
296         >>> print ':'.join(seq4)
297         boy:good:doiido:hello
298 
299 
300         #合并目录
301 
302         >>> import os
303         >>> os.path.join('/hello/','good/boy/','doiido')
304         '/hello/good/boy/doiido'
305 
306 
307         S.join(iterable) -> str
308 
309         Return a string which is the concatenation of the strings in the
310         iterable.  The separator between elements is S.
311         """
312         return ""
313 
314     def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
315         """
316         S.ljust(width[, fillchar]) -> str
317 
318         Return S left-justified in a Unicode string of length width. Padding is
319         done using the specified fill character (default is a space).
320         """
321         return ""
322 
323     def lower(self): # real signature unknown; restored from __doc__
324         """
325         S.lower() -> str
326 
327         Return a copy of the string S converted to lowercase.
328         """
329         return ""
330 
331     def lstrip(self, chars=None): # real signature unknown; restored from __doc__
332         """
333         S.lstrip([chars]) -> str
334 
335         Return a copy of the string S with leading whitespace removed.
336         If chars is given and not None, remove characters in chars instead.
337         """
338         return ""
339 
340     def maketrans(self, *args, **kwargs): # real signature unknown
341         """
342         Return a translation table usable for str.translate().
343 
344         If there is only one argument, it must be a dictionary mapping Unicode
345         ordinals (integers) or characters to Unicode ordinals, strings or None.
346         Character keys will be then converted to ordinals.
347         If there are two arguments, they must be strings of equal length, and
348         in the resulting dictionary, each character in x will be mapped to the
349         character at the same position in y. If there is a third argument, it
350         must be a string, whose characters will be mapped to None in the result.
351         """
352         pass
353 
354     def partition(self, sep): # real signature unknown; restored from __doc__
355         """
356         以sep为分割,将S分成head,sep,tail三部分
357 
358         S.partition(sep) -> (head, sep, tail)
359 
360         Search for the separator sep in S, and return the part before it,
361         the separator itself, and the part after it.  If the separator is not
362         found, return S and two empty strings.
363         """
364         pass
365 
366     def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
367         """
368         S.replace(old, new[, count]) -> str
369 
370         Return a copy of S with all occurrences of substring
371         old replaced by new.  If the optional argument count is
372         given, only the first count occurrences are replaced.
373         """
374         return ""
375 
376     def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
377         """
378         S.rfind(sub[, start[, end]]) -> int
379 
380         Return the highest index in S where substring sub is found,
381         such that sub is contained within S[start:end].  Optional
382         arguments start and end are interpreted as in slice notation.
383 
384         Return -1 on failure.
385         """
386         return 0
387 
388     def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
389         """
390         S.rindex(sub[, start[, end]]) -> int
391 
392         Like S.rfind() but raise ValueError when the substring is not found.
393         """
394         return 0
395 
396     def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
397         """
398         S.rjust(width[, fillchar]) -> str
399 
400         Return S right-justified in a string of length width. Padding is
401         done using the specified fill character (default is a space).
402         """
403         return ""
404 
405     def rpartition(self, sep): # real signature unknown; restored from __doc__
406         """
407         S.rpartition(sep) -> (head, sep, tail)
408 
409         Search for the separator sep in S, starting at the end of S, and return
410         the part before it, the separator itself, and the part after it.  If the
411         separator is not found, return two empty strings and S.
412         """
413         pass
414 
415     def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
416         """
417         S.rsplit(sep=None, maxsplit=-1) -> list of strings
418 
419         Return a list of the words in S, using sep as the
420         delimiter string, starting at the end of the string and
421         working to the front.  If maxsplit is given, at most maxsplit
422         splits are done. If sep is not specified, any whitespace string
423         is a separator.
424         """
425         return []
426 
427     def rstrip(self, chars=None): # real signature unknown; restored from __doc__
428         """
429         S.rstrip([chars]) -> str
430 
431         Return a copy of the string S with trailing whitespace removed.
432         If chars is given and not None, remove characters in chars instead.
433         """
434         return ""
435 
436     def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
437         """
438         以sep为分割,将S切分成列表,与partition的区别在于切分结果不包含sep,
439         如果一个字符串中包含多个sep那么maxsplit为最多切分成几部分
440         >>> a='a,b c\nd\te'
441         >>> a.split()
442         ['a,b', 'c', 'd', 'e']
443         S.split(sep=None, maxsplit=-1) -> list of strings
444 
445         Return a list of the words in S, using sep as the
446         delimiter string.  If maxsplit is given, at most maxsplit
447         splits are done. If sep is not specified or is None, any
448         whitespace string is a separator and empty strings are
449         removed from the result.
450         """
451         return []
452 
453     def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
454         """
455         Python splitlines() 按照行('\r', '\r\n', \n')分隔,
456         返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如        果为 True,则保留换行符。
457         >>> x
458         'adsfasdf\nsadf\nasdf\nadf'
459         >>> x.splitlines()
460         ['adsfasdf', 'sadf', 'asdf', 'adf']
461         >>> x.splitlines(True)
462         ['adsfasdf\n', 'sadf\n', 'asdf\n', 'adf']
463 
464         S.splitlines([keepends]) -> list of strings
465 
466         Return a list of the lines in S, breaking at line boundaries.
467         Line breaks are not included in the resulting list unless keepends
468         is given and true.
469         """
470         return []
471 
472     def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
473         """
474         S.startswith(prefix[, start[, end]]) -> bool
475 
476         Return True if S starts with the specified prefix, False otherwise.
477         With optional start, test S beginning at that position.
478         With optional end, stop comparing S at that position.
479         prefix can also be a tuple of strings to try.
480         """
481         return False
482 
483     def strip(self, chars=None): # real signature unknown; restored from __doc__
484         """
485         S.strip([chars]) -> str
486 
487         Return a copy of the string S with leading and trailing
488         whitespace removed.
489         If chars is given and not None, remove characters in chars instead.
490         """
491         return ""
492 
493     def swapcase(self): # real signature unknown; restored from __doc__
494         """
495         大小写反转
496         S.swapcase() -> str
497 
498         Return a copy of S with uppercase characters converted to lowercase
499         and vice versa.
500         """
501         return ""
502 
503     def title(self): # real signature unknown; restored from __doc__
504         """
505         S.title() -> str
506 
507         Return a titlecased version of S, i.e. words start with title case
508         characters, all remaining cased characters have lower case.
509         """
510         return ""
511 
512     def translate(self, table): # real signature unknown; restored from __doc__
513         """
514         table=str.maketrans('alex','big SB')
515 
516         a='hello abc'
517         print(a.translate(table))
518 
519         S.translate(table) -> str
520 
521         Return a copy of the string S in which each character has been mapped
522         through the given translation table. The table must implement
523         lookup/indexing via __getitem__, for instance a dictionary or list,
524         mapping Unicode ordinals to Unicode ordinals, strings, or None. If
525         this operation raises LookupError, the character is left untouched.
526         Characters mapped to None are deleted.
527         """
528         return ""
529 
530     def upper(self): # real signature unknown; restored from __doc__
531         """
532         S.upper() -> str
533 
534         Return a copy of S converted to uppercase.
535         """
536         return ""
537 
538     def zfill(self, width): # real signature unknown; restored from __doc__
539         """
540         原来字符右对齐,不够用0补齐
541 
542         S.zfill(width) -> str
543 
544         Pad a numeric string S with zeros on the left, to fill a field
545         of the specified width. The string S is never truncated.
546         """
547         return ""
548 
549      ...略...
View Code

列表

列表的定义和创建

定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素

列表的创建:

>>> list_test = ['ike', 'jack', 'deny']
>>> list_test
['ike', 'jack', 'deny']
>>> list_test = list('ike')
>>> list_test
['i', 'k', 'e']
>>> list_test = list(['王大', '李五', '赵六'])
>>> list_test
['王大', '李五', '赵六']

列表的特点和常用操作

特性:

1.可以存放多个指

2.按照从左往右的顺序定义列表元素,下标从0开始顺序访问,有序:

3.可以修改指定索引的值,可变

常用操作:

 1 # 索引取值
 2 >>> we = ['test1', 'test2', 'test3']
 3 >>> we[0]
 4 'test1'
 5 >>> we[2]
 6 'test3'
 7 >>> we[1]
 8 'test2'
 9 >>> we[-1]
10 'test3'
11 >>> we[-2]
12 'test2'
 1 # 切片用法
 2 >>> we
 3 ['test1', 'test2', 'test3', 'test4']
 4 >>> we.append('test5')
 5 >>> we
 6 ['test1', 'test2', 'test3', 'test4', 'test5']
 7 >>> we[0:3]
 8 ['test1', 'test2', 'test3']
 9 >>> we[2:10]
10 ['test3', 'test4', 'test5']
11 >>> we[:4]
12 ['test1', 'test2', 'test3', 'test4']
13 >>> we[2:5]
14 ['test3', 'test4', 'test5']
15 >>> we[:]
16 ['test1', 'test2', 'test3', 'test4', 'test5']
17 >>> we[::2]
18 ['test1', 'test3', 'test5']
19 >>> we[::-1]
20 ['test5', 'test4', 'test3', 'test2', 'test1']
1 # 追加
2 >>> we.append('test6')
3 >>> we
4 ['test1', 'test2', 'test3', 'test4', 'test5', 'test6']
5 >>> we.append('test7')
6 >>> we
7 ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7']
# 删除
>>> we.pop()
'test7'
>>> we
['test1', 'test2', 'test3', 'test4', 'test5', 'test6']
>>> we.remove('test4')
>>> we
['test1', 'test2', 'test3', 'test5', 'test6']
>>> we.pop(2)
'test3'
>>> we
['test1', 'test2', 'test5', 'test6']
1 # 长度
2 >>> len(we)
3 4
# 包含
>>> we
['test1', 'test2', 'test5', 'test6']
>>> 'test1' in we
True
>>> 'test100' in we
False
 1 # 遍历类表中的值
 2 >>> we
 3 ['test1', 'test2', 'test5', 'test6']
 4 >>> for i in we:
 5 ...     print(i)
 6 ...
 7 test1
 8 test2
 9 test5
10 test6

列表与字符串——split和join

# 分割
>>> we = 'hello everyone'
>>> we.split(' ')
['hello', 'everyone']
>>> we = 'hello,everyone'
>>> we.split(',')
['hello', 'everyone']
# 连接
>>> we = ['he', 'llo']
>>> ''.join(we)
'hello'
>>> '@'.join(we)
'he@llo'

布尔型

布尔型数据,就是一个真(True),一个假(False),用于逻辑判断。举例说明:

>>> 3 > 5  # 3大于5不成立,显示假(False)
False
>>> 3 <5  # 3小于5成绩,显示真(True)
True

计算机用这种类型判断不同的事件了.比如:

a = 2
b = 5
if a > b:
    print('这是错的')
else:
    print('应该是小于')
range的用法

思考:现在我们创建一个从1-100的列表,我们该怎么创建?

1.从1写到100  # 纯手工操作,耗时费力,及容易出错

2.for循环取1-100  # 效率比较快,但还不是最简单

3.range方法  # 简单,高效

 1 >>> list(range(100))
 2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
 3 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
 4  56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82
 5 , 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
 6 >>> list(range(1,100))
 7 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
 8  30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56
 9 , 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 8
10 3, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
11 >>> list(range(10))
12 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
13 >>> list(range(0,100,2))
14 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54,
15  56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]
View Code

总结:本文介绍初次认识数字,字符串,列表,布尔类型和常用的方法及布尔类型的基本逻辑判断。

转载于:https://www.cnblogs.com/cnike/p/10431304.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值