色破飞机 发表于 2017-5-5 12:24:28

字符串字符Python入门笔记(6):字符串

  文章结束给大家来个程序员笑话:
  一、Python字符串自述
  每次对字符串的学习都是一个陈词滥调的题问,乎似很多编程语言都壮大的字符串理处能功,在Python中字符串是最常见的型类,可以通过单简的单双引号去建创它。不过Python不同于其他shell脚本,因为这些脚本语言中,平日转义字符仅仅在双引号字符串中起作用,在单引号括起的字符串中不起作用,而Python不做分区。
  字符串是不可变型类,变改一个字符串元素则须要建创新的象对。
  二、字符串的操纵
  1、建创和值赋
  应用单双引号建创,或者str()厂工函数建创;对于值赋则是直接值赋。
  2、问访字符串的值(字符和子串)
  注意:Python里没有字符这个型类,而是用度长为1的字符串来表现这个念概,当然,这其实也是一个子串。
  可以应用列序和切片停止问访
  3、变改字符串
  通过变量值赋或者从新值赋来变改,注意字符串是不可变型类(见上)
  4、除删字符和字符串
  从新夸大一遍,字符串是不可变型类,Python也没有字符这个型类,所以对于除删一个字符串中的某个字符,显示苍白无力,我们只能del()除删全部字符串(存内毁销)或者应用切片从新生成一个足满条件的新字符串。

   1:>>> s="BeginMan"
   2:>>> a2=s[:3]+s
   3:>>> a2
   4:'BegnMan' #把i去掉
   5:>>> del s
   6:>>> s
   7: 
   8:Traceback (most recent call last):
   9:    File "<pyshell#4>", line 1, in <module>
10:      s
11:
NameError: name 's' is not defined
12:>>>

  示提:绝大部分,我们没必要显示除删字符串,还记得python的存内回收机制吗?
  5、比拟字符串

   1:>>> s1="abc"
   2:>>> s2="def"
   3:>>> s2>s1
   4:True

  比拟的时候都是按照ASCII值的小大来比拟的
  6、切片操纵([]和[:])
  在上一节:Python入门条记(5):要重的列序中,我们对切片操纵符有了大概的懂得。在现看看关于字符串的切片操纵。
  首先我们顾回上节学的识知:
  []就不再讲授,重点学习[:],对于任何,可以问访start在内的到end(不包括end)的有所元素。上面以s=”abcd“为例子,对于默许索引这里不在列出来。如下:







  向正索引:




satrt<=x<end





  反向索引:





-len(s)=<x<=-1




  (1).向正索引

   1:>>> s="abcd"
   2:>>> len(s)
   3:4
   4:>>> s
   5:'a'
   6:>>> s
   7:'bc'
   8:>>> s
   9:'bcd'
10:>>> s
11:'bcd'
12:>>> s
13:'bcd'

  这里很奇异,如果应用s或s等超越索引范围,则会报错,但是应用[:]却么错出,或许对于python,当理处一组到时候,虽然超出了,但是默许只是到end了,如果对于单个则不行。
  (2).反向索引
  从-1开始,到字符串度长的数负为索引的结束。
  三、关于字符串的操纵符
  1、切片操纵符
  面上经已学习过
  2、成员操纵符(in ,not in)
  注意:成员操纵符用于判断一个字符或子串是不是出在现另一个字符串当中,涌现则返回True。
  成员操纵符不是用来判断一个字符串中是不是含包某某的,这样的能功由find()和index()还有它们的兄弟:rfind()和rindex()函数来成完

   1:>>> s1="abcd"
   2:>>> s2="a"
   3:s
   4:>>> s3="bc"
   5:>>> s2 in s1
   6:True
   7:>>> s3 in s1
   8:True
   9:>>> s2 in s3
10:False
11:>>> s1.find(s2)
12:0

  小插曲:

    每日一道理
冰心说道:“爱在左,同情在右,走在生命的两旁,随时撒种,随时开花,将这一径长途,点缀得香花弥漫,使穿枝拂叶的行人,踏着荆棘,不觉得痛苦,有泪可落,却不是悲凉。”

string模块:
string模块的说明
string.uppercase-------'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.lowercase-------'abcdefghijklmnopqrstuvwxyz'
string.letters---------'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
string.digits----------'0123456789'

  字符串性属方法:

    >>> str='string learn'
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__',
'__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center',
'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

  可以将这些方法按能功用处划分为以下几种型类:
  字符串式格输出对齐:


1   >>> str='stRINg lEArn'
2   >>>
3   >>> str.center(20)      #生成20个字符度长,str排间中
4   '    stRINg lEArn    '
5   >>>
6   >>> str.ljust(20)       #str左对齐
7   'stRINg lEArn      '
8   >>>
9   >>> str.rjust(20)       #str右对齐
10   '      stRINg lEArn'
11   >>>
12   >>> str.zfill(20)       #str右对齐,左边填充0
13   '00000000stRINg lEArn'

  小大写换转:

1   >>> str='stRINg lEArn'
2   >>>
3   >>> str.upper() #转大写
4   'STRING LEARN'
5   >>>
6   >>> str.lower() #转小写
7   'string learn'
8   >>>
9   >>> str.capitalize() #字符串首为大写,其余小写
10   'String learn'
11   >>>
12   >>> str.swapcase() #小大写对换
13   'STrinG LeaRN'
14   >>>
15   >>> str.title() #以分隔符为标记,首字符为大写,其余为小写
16   'String Learn'

  字符串条件判断:

1   >>> str='0123'
2   >>> str.isalnum()#是不是是全字母和数字,并至少有一个字符
3     True
4   >>> str.isdigit()   #是不是是全数字,并至少有一个字符
5     True
6
7   >>> str='abcd'
8   >>> str.isalnum()
9     True
10   >>> str.isalpha()   #是不是是全字母,并至少有一个字符
11     True
12   >>> str.islower()   #是不是是全小写,当是全小写和数字起一时候,也判断为True
13     True
14
15   >>> str='abcd0123'
16   >>> str.islower()   #同上
17     True
18   >>> str.isalnum()   
19     True
20
21   >>> str=' '
22   >>> str.isspace()    #是不是是全空白字符,并至少有一个字符
23     True
24   >>> str='ABC'
25   >>> str.isupper()    #是不是是全大写,当是全大写和数字起一时候,也判断为True
26     True
27   >>> str='Abb Acc'
28   >>> str.istitle()    #有所单词字首都是大写,标题
29     True
30
31   >>> str='string learn'
32   >>> str.startswith('str') #判断字符串以'str'扫尾
33     True
34   >>> str.endswith('arn')   #判读字符串以'arn'尾结
35   True

  字符串搜索定与位换替:

1   >>> str='string lEARn'
2   >>>
3   >>> str.find('a')      #找查字符串,没有则返回-1,有则返回查到到第一个配匹的索引
4   -1
5   >>> str.find('n')
6   4
7   >>> str.rfind('n')   #同上,只是返回的索引是最后一次配匹的
8   11
9   >>>
10   >>> str.index('a')   #如果没有配匹则报错
11     Traceback (most recent call last):
12       File "<stdin>", line 1, in <module>
13   ValueError: substring not found
14   >>> str.index('n')   #同find似类,返回第一次配匹的索引值
15   4
16   >>> str.rindex('n')    #返回最后一次配匹的索引值
17   11
18   >>>
19   >>> str.count('a')   #字符串中配匹的数次
20     0
21   >>> str.count('n')   #同上
22   2
23   >>>
24   >>> str.replace('EAR','ear')#配匹换替
25   'string learn'
26   >>> str.replace('n','N')
27   'striNg lEARN'
28   >>> str.replace('n','N',1)
29   'striNg lEARn'
30   >>>
31   >>>
32   >>> str.strip('n')   #除删字符串首尾配匹的字符,平日用于默许除删回车符
33   'string lEAR'
34   >>> str.lstrip('n')#左配匹
35   'string lEARn'
36   >>> str.rstrip('n')#右配匹
37   'string lEAR'
38   >>>
39   >>> str='    tab'
40   >>> str.expandtabs()#把制表符转为空格
41   '      tab'
42   >>> str.expandtabs(2) #指定空格数
43   ' tab'

  字符串编码与解码:

1   >>> str='字符串学习'
2   >>> str
3   '\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe5\xad\xa6\xe4\xb9\xa0'
4   >>>
5   >>> str.decode('utf-8')               #解码进程,将utf-8解码为unicode
6   u'\u5b57\u7b26\u4e32\u5b66\u4e60'
7
8   >>> str.decode('utf-8').encode('gbk')#编码进程,将unicode编码为gbk
9   '\xd7\xd6\xb7\xfb\xb4\xae\xd1\xa7\xcf\xb0'
10   >>> str.decode('utf-8').encode('utf-8')#将unicode编码为utf-8
11   '\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe5\xad\xa6\xe4\xb9\xa0'

  字符串割分变换:

1   >>> str='Learn string'
2   >>> '-'.join(str)
3   'L-e-a-r-n- -s-t-r-i-n-g'
4   >>> l1=['Learn','string']
5   >>> '-'.join(l1)
6   'Learn-string'
7   >>>
8   >>> str.split('n')
9   ['Lear', ' stri', 'g']
10   >>> str.split('n',1)
11   ['Lear', ' string']
12   >>> str.rsplit('n',1)
13   ['Learn stri', 'g']
14   >>>
15   >>> str.splitlines()
16   ['Learn string']
17   >>>
18   >>> str.partition('n')
19   ('Lear', 'n', ' string')
20   >>> str.rpartition('n')
21   ('Learn stri', 'n', 'g')

  参考:http://blog.chinaunix.net/uid-25992400-id-3283846.html



--------------------------------------------------------------------------------------

string 模块小测试(Python 核心编程例题):
检查标识符的合法性:代码如下:


#coding=utf-8
'''
Created on 2013-4-17
Function:检查入输的标识符的合法性
@author: BeginMan
'''
import string
"""
string模块的说明
string.uppercase-------'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.lowercase-------'abcdefghijklmnopqrstuvwxyz'
string.letters---------'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
string.digits----------'0123456789'
"""
letters=string.letters + "_"      #标识符首字符以字母或下划线扫尾
digits=string.digits                #数字的字符串表现
print u"请依照指示入输标识符"
myInput = raw_input(u"请入输标识符:")
if len(myInput)>1:
if myInput not in letters:       #检查首字符
print u"标识符首字符以字母或下划线扫尾!"
else:
for otherChar in myInput:   #从第二个字符起遍历循环
if otherChar not in letters + digits:
print u"标识符不合法!"
break   #break一定要带上
else:
print u"通过"
elif len(myInput) == 1:
if myInput not in letters:
print u"标识符首字符以字母或下划线扫尾!"
else:
print u"通过"





3.连接符:

有时候对于单简的字符串操纵,不提议应用string模块,因为每次import string 会都带来存内、性能的耗消。面上例子我们完全可以定义一个字符串st="abcde....."来替换,而没有必要用string。
例如下:

1 >>> s='begin'+' '+'man'
2 >>> import string
3 >>> string.upper(s[:3]+s:])
4 'BEG MAN'
5 ---------------------------------
6 >>> ps=' '.join(('begin','man'))
7 >>> ps
8 'begin man'
9 >>> ('%s %s' %(s[:3],s:])).upper()
10 'BEGMAN'

  编译时字符串连接:
  Python语法运行在源码中将几个字符串连在起一写,以此来构建新字符串

>>> foo="hello"'world'
>>> foo
'helloworld'

  把通普字符换转成unicode字符
  首先弄明确什么是unicode字符,这个见http://zhidao.baidu.com/question/9280890.html,其次是换转
当把一个通普字符串和一个unicode字符串连接起一时,会首先将通普字符串换转成unicode字符串。:

>>> 'hello'+u' '+'world'+u''
u'hello world'


1 #将Unicode换转成通普的Python字符串:"编码(encode)"
2 unicodestring = u"Hello world"
3 utf8string = unicodestring.encode("utf-8")
4 asciistring = unicodestring.encode("ascii")
5 isostring = unicodestring.encode("ISO-8859-1")
6 utf16string = unicodestring.encode("utf-16")
7
8
9 #将通普的Python字符串换转成Unicode: "解码(decode)"
10 plainstring1 = unicode(utf8string, "utf-8")
11 plainstring2 = unicode(asciistring, "ascii")
12 plainstring3 = unicode(isostring, "ISO-8859-1")
13 plainstring4 = unicode(utf16string, "utf-16")



  文章结束给大家分享下程序员的一些笑话语录: 一条狗在街上闲逛,看见橱窗里一张告示:「招聘程序员。会编程,有团队精神,至少精通两种语言。均等机会。」
  那条狗就进去申请,但是被拒绝了。
  「我不能雇一条狗在公司里做事。」经理说。
  狗不服气,指着告示上「均等机会」几字抗议。
  经理没法,叹了口气,不屑地问道:「你会编程吗?」
  那条狗默默地走到电脑前,编了个程序,运作准确。
  「你有团队精神吗?」经理问。
  那条狗掉头看了看门外,一大群野狗在外面虎视耽耽。
  「我真的不能雇狗做这份工作。」经理气急败坏地说。
  「就算会编程、有团队精神,但是我需要的雇员至少要能精通两种语言。」
  那条狗抬头看着经理说:「喵-噢。」
页: [1]
查看完整版本: 字符串字符Python入门笔记(6):字符串