编程自己常见error(3)

继续上一篇进行总结。

编程自己常见error(3)

11、关于split()函数

在学习的过程中遇到split()函数,也就是通过指定分隔符对字符串进行切片,分隔。
分割的时候:分隔符,默认为所有的空字符,包括空格(space)、换行(\n)、制表符(\t)等。
当我们指定分隔数量时候,就会按照数量来。我自己大致总结了几种关于这个函数的用法:

  • 示例1 简单分隔
a = "nihao \nnero chang \nGood	morning"
print a

print a.split()
print a.split(' ', 1)
print a.split(' ', 2)
print a.split(' ', 3)

运行结果是:

nihao
nero chang
Good    morning
['nihao', 'nero', 'chang', 'Good', 'morning']
['nihao', '\nnero chang \nGood\tmorning']
['nihao', '\nnero', 'chang \nGood\tmorning']
['nihao', '\nnero', 'chang', '\nGood\tmorning']

没有标明分割数目的时候,他将所有的都分隔;当表明分隔数目时,就会从左到右依次进行分隔。

  • 示例2指定字符分隔
b = 'ni+hao_zzc'
print b.split('+')
print b.split('_')

运行结果是:

['ni', 'hao_zzc']
['ni+hao', 'zzc']

第一个输出按照+分隔,第二个输出按照 _分隔。

  • 示例3
str= "https://me.csdn.net/weixin_41122036"
print "0: %s " % str.split("/")[-1]
print "1: %s " % str.split("/")[-2]
print "2: %s " % str.split("/")[-3]
print "3: %s " % str.split("/")[-4]

print "4: %s " % str.split("/", -1)
print "5: %s " % str.split("/", 0)
print "6: %s " % str.split("/", 1)
print "7: %s " % str.split("/", 2)
print "8: %s " % str.split("/", 3)
print "9: %s " % str.split("/", 4)

运行结果是:

0: weixin_41122036
1: me.csdn.net
2:
3: https:
4: ['https:', '', 'me.csdn.net', 'weixin_41122036']
5: ['https://me.csdn.net/weixin_41122036']
6: ['https:', '/me.csdn.net/weixin_41122036']
7: ['https:', '', 'me.csdn.net/weixin_41122036']
8: ['https:', '', 'me.csdn.net', 'weixin_41122036']
9: ['https:', '', 'me.csdn.net', 'weixin_41122036']

前四个的输出,将这个网址看成是一个列表,将分隔出来的数据一次按照对应的编码显示出来。
后六个的输出是将/看作分隔符来分隔,并写下来分隔的份数,进行相对应的显示。

  • 示例4 将分隔符两侧数据分别重新赋值,得到自己想要的数据。
c = 'zzcse@focmail.com'
c1, c2 = c.split('@')
print c1
print c2

运行结果是:

zzcse
focmail.com
  • 示例5 多种分隔符的一次性分隔
import re
d = "My; name*is+ zzc."
e = re.split(';|\*|\+ ', d)
print e

g = 'Beautiful, is; better*than\nugly'
x = re.split(',|; |\*|\n',g)
print x

运行结果是:

['My', ' name', 'is', 'zzc.']
['Beautiful', ' is', 'better', 'than', 'ugly']

这个是引入了re模块,一个字符串可能有很多不一样的分隔,我们想一次性分隔出来,就能用到这个模块,很好用。(可以在Powershell中输入python -m pydoc re查看他的文档,也就是file
示范:

PS C:\Users\15222> python -m pydoc re
>>>

显示如下:


PS C:\Users\15222> python -m pydoc re
Help on module re:

NAME
    re - Support for regular expressions (RE).

FILE
    c:\python27\lib\re.py

DESCRIPTION
    This module provides regular expression matching operations similar to
    those found in Perl.  It supports both 8-bit and Unicode strings; both
    the pattern and the strings being processed can contain null bytes and
    characters outside the US ASCII range.

    Regular expressions can contain both special and ordinary characters.
    Most ordinary characters, like "A", "a", or "0", are the simplest
    regular expressions; they simply match themselves.  You can
    concatenate ordinary characters, so last matches the string 'last'.

    The special characters are:
        "."      Matches any character except a newline.
        "^"      Matches the start of the string.
        "$"      Matches the end of the string or just before the newline at
                 the end of the string.
        "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
                 Greedy means that it will match as many repetitions as possible.
        "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
        "?"      Matches 0 or 1 (greedy) of the preceding RE.
        *?,+?,?? Non-greedy versions of the previous three special characters.
        {m,n}    Matches from m to n repetitions of the preceding RE.
        {m,n}?   Non-greedy version of the above.
        "\\"     Either escapes special characters or signals a special sequence.
        []       Indicates a set of characters.
                 A "^" as the first character indicates a complementing set.
        "|"      A|B, creates an RE that will match either A or B.
        (...)    Matches the RE inside the parentheses.
                 The contents can be retrieved or matched later in the string.
-- More  --

12、OrderedDict (有序字典)

我在学习字典这个部分的时候,发现一般是出来的时候,顺序都是比较随机的,每次顺序都不一样(对应关系肯定是一样的),然后我就发现了有序字典这个神器!!!
正常的字典:

scenes ={
				'elf_room':' ElfRoom()',
				'tiger_room': 'TigerRoom()',
				'baby_room':'BabyRoom()',
				'einstein_room':'EinsteinRoom()',
				'dragon_room':'DragonRoom()',
				'reading_room':'ReadingRoom()',
				'death':'Death()'
				}
				
print scenes

运行结果是:

PS C:\Users\15222\lpthw> python dic.py
{'einstein_room': 'EinsteinRoom()', 'baby_room': 'BabyRoom()', 'reading_room': 'ReadingRoom()', 'tiger_room': 'TigerRoom()', 'death': 'Death()', 'dragon_room': 'DragonRoom()', 'elf_room': ' ElfRoom()'}

运行结果和原来的代码顺序是不同的。
有序字典就是记住了代码中的顺序,进行顺序输出:

from collections import OrderedDict
import collections

reg_scenes ={
				'elf_room':' ElfRoom()',
				'tiger_room': 'TigerRoom()',
				'baby_room':'BabyRoom()',
				'einstein_room':'EinsteinRoom()',
				'dragon_room':'DragonRoom()',
				'reading_room':'ReadingRoom()',
				'death':'Death()'
				}
				
for a, b in reg_scenes.items():
	print a, b



print '-----------------------'
ord_scenes = {}
ord_scenes = collections.OrderedDict()
ord_scenes['elf_room'] = 'ElfRoom()'
ord_scenes['tiger_room'] = 'TigerRoom()'				
ord_scenes['baby_room'] = 'BabyRoom()'
ord_scenes['einstein_room'] = 'EinsteinRoom()'
ord_scenes['dragon_room'] = 'DragonRoom()'
ord_scenes['reading_room'] = 'ReadingRoom()'
ord_scenes['death'] = 'Death()'					

for a, b in ord_scenes.items():
	print a, b

运行结果是:

PS C:\Users\15222\lpthw> python dic.py
einstein_room EinsteinRoom()
baby_room BabyRoom()
reading_room ReadingRoom()
tiger_room TigerRoom()
death Death()
dragon_room DragonRoom()
elf_room  ElfRoom()
-----------------------
elf_room ElfRoom()
tiger_room TigerRoom()
baby_room BabyRoom()
einstein_room EinsteinRoom()
dragon_room DragonRoom()
reading_room ReadingRoom()
death Death()

为了看出来对比,又完善了一下代码,嘻嘻。
这就能比较明显的看出来了,正常情况下,是没有记忆顺序的;但是顺序字典,记住了字典的顺序,并顺序输出。

13、类遇到的问题

刚开始学习类的时候,遇到了很奇葩的问题,纠结了好一会:就是写的初始函数部分,总是报错,几乎绝望…最后我发现新手可能犯的错误,我都中枪了!!

  1. 类 初始化函数 init 以为写对了,其实错了,因为左右都是2个下划线。是左边两个!!右边也是两个!!!不是合计2个!!!__init__!!!
  2. init写成Int ,忘记i,粗心的代价。
    这真的是坑可我很久,我自己看了半天没看出来错误 哈啊哈,尴尬 眼睛还是不够犀利,还有经验不够。
  3. 类的格式一定要比较熟悉,初学的时候我总是忘记这,丢掉那。
  4. 在进行类中内容书写的过程中, 我们一定要注意到变量的使用,self.xxxxx 不然系统会自动认作全局变量,当作你没有定义。这个错误我犯过两次,就记住了。
  • 父类的写法
class 类名+object):
	def __init__(self,变量1,变量2...):
		self.变量1 = 变量1
		self.变量2 = 变量2
		...
	def 函数1(self):
		pass
	def 函数2(self):
		pass
	...
  • 子类的写法:
class 类名+(父类名):
	def __init__(self,变量1,变量2...):
		self.变量1 = 变量1
		self.变量2 = 变量2
		...
	def 函数1(self):
		pass
	def 函数2(self):
		pass
	...

基本格式还是要记清楚。

14、编程的缩进问题

  • python对于空格键和Tab键的混用是极其反感的!!!
  • 尽量开始就要养成良好的编程习惯,不能因为这些错误,耽误大量时间调试。
  • 在编译时会出现这样的错IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值