python学习之字符串

来源:互联网 发布:东京女子图鉴 知乎 编辑:程序博客网 时间:2024/06/14 23:41



######字符串######
重点知识:
 面试题案例: 123和“123”一样么?
  - 从数字角度讲    是一样的
  - 从程序语言的识别来讲  不一样(下面进行验证)
[root@server ~]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 123  ##给a赋值123
>>> b = "123"  ##给b赋值"123"
>>> a == b  ##检测ab是否相等
False   ##输出波尔值为false表示不相等
>>> print a  
123
>>> print b
123
>>> type(a)  
<type 'int'>  ##a的类型为整型,而b的类型为字符型
>>> type(b)
<type 'str'>


1.数字的类型 整型  长整型 浮点型  复数类型
[root@server ~]# python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> num1 = 333  
>>> type(num1) 
<type 'int'>   ##整型
>>> type(333)
<type 'int'>
>>> num2 = 99999999999999999999999999999999999999999999999999999 
>>> type(num2)
<type 'long'>   ##长整型
>>> num3 = 333L   ##强制设置为长整型
>>> type(num3)
<type 'long'>
>>> a1 = 3
>>> type(a1)
<type 'int'>
>>> a2 = 3.0   
>>> type(a2)
<type 'float'>   ##浮点型
>>> a3 = 8.32e-36j  
>>> type(a3)
<type 'complex'>  ##复数类型
>>>

 
2.字符串
*字符串属于序列,序列支持的操作如下:
 • 索引 切片
 • 判断子串 重复
 • 连接
   计算长度
字符串的三种定义方式
>>> str1 = 'hello westos' ##单引号
>>> str2 = "hello westos" ##双引号
>>> str3 = """hello westos""" ##三双引
>>> type(str1)   ##类型都为字符串
<type 'str'>
>>> type(str2)
<type 'str'>
>>> type(str3)
<type 'str'>
>>> print str1   ##内容相同
hello westos
>>> print str2
hello westos
>>> print str3
hello westos

转义字符
一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符
\n: 代表换行符  \": 代表双引号本身
\t: 代表tab符  \': 代表单引号本身


>>> say = 'let's go'  ##三个单引号无法配对,提示语法错误
  File "<stdin>", line 1
    say = 'let's go'
               ^
SyntaxError: invalid syntax
>>> say = 'let\'s go'  ##使用转义字符取消特殊意义
>>> say
"let's go"
>>> say = "let's go"  ##使用双引号
>>> say
"let's go"
>>> mail = "tom: morning  i am juff"
>>> print mail
tom: morning  i am juff
>>> mail = "tom: \n morning\n i am juff"
>>> print mail
tom:
 morning
 i am juff


三重引号
.块注释
  函数的doc文档 *
  字符串格式化

>>> mail = """tom:   ##格式化显示
...             nice to meet you!
...             what's you name?
... """
>>> print mail
tom:
  nice to meet you!
  what's you name?

>>> mail
"tom:\n\t\tnice to meet you!\n\t\twhat's you name?\n"


字符串索引
• 索引(s[i] ):获取特定偏移的元素
• 给出一个字符串,可输出任意一个字符,如果索引为负数,就是相当于从后向前数。
>>> a = 'howareyou'
>>> type(a)
<type 'str'>
>>> a[0]  ##取出字符串的第一位
'h'
>>> a[1]
'o'
>>> a[0]+a[1]  ##取出第一位和第二位
'ho'


字符串切片
切片S[i:j]提取对应的部分作为一个序列:
 •上边界并不包含在内;
 •如果没有给出切片的边界,切片的下边界默认为0,上边界为字符串的长度;
 •扩展的切片S[i:j:k],其中i,j含义同上,k为递增步长;
  s[:]获取从偏移量为0到末尾之间的元素,是实现有效拷贝的一种方法
>>> a[1:4:1]  ##取出第二位到第四位,步长为1
'owa'
>>> a[2:6]  ##取出第三位到第五位
'ware'
>>> a[8:1]  ##python默认从左到右取值
''
>>> a[:]  ##第一个不设置默认0,后面不设置默认总长度
'howareyou'
>>> a[-1]
'u'
>>> a[-3:-1]
'yo'
>>>


判断子串
判断一个sub字符串是不是属于s字符串:
•sub in s      输出布尔值ture false
•sub not in s

[root@server ~]# ipython
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
Type "copyright", "credits" or "license" for more information.

IPython 3.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.


In [1]: a = "westos"  

In [2]: "s" in a  ##判断a中是否含有"s",有则输出true,没有则输出false
Out[2]: True

In [3]: "a" in a  ##判断a中是否含有"a"
Out[3]: False

In [4]: "b" not in a
Out[4]: True

重复、连接及计算长度


In [5]: print '#####'*10  ##重复打印
##################################################

In [6]: s = 'hello westos'  

In [7]: len(s)    ##计算长度
Out[7]: 12

In [8]: print 'i'+' love'+' you' ##连接
i love you


字符串的类型转换
*字符串常用操作:
In [2]: a = "westos"

In [3]: a
Out[3]: 'westos'

In [4]: type(a)
Out[4]: str

In [5]: a.     ##*字符串常用操作
a.capitalize  a.format      a.isupper     a.rindex      a.strip
a.center      a.index       a.join        a.rjust       a.swapcase
a.count       a.isalnum     a.ljust       a.rpartition  a.title
a.decode      a.isalpha     a.lower       a.rsplit      a.translate
a.encode      a.isdigit     a.lstrip      a.rstrip      a.upper
a.endswith    a.islower     a.partition   a.split       a.zfill
a.expandtabs  a.isspace     a.replace     a.splitlines 
a.find        a.istitle     a.rfind       a.startswith 


str.capitalize() - 将字符串首字母大写,并返回新的首字母大写后的字符串;
In [6]: a.capitalize()
Out[6]: 'Westos'


str.center(width[,fillchar]) - 返回一个长为width的新字符串,在新字符串中原字符居中,其他部分用fillchar指定的符号填充,未指定时通过空格填充。
In [7]: a.center(10)
Out[7]: '  westos  '

In [8]: a.center(10,'*')
Out[8]: '**westos**'

In [9]: "Welcome to manage system".center(20,"*") ##以*补齐
Out[9]: 'Welcome to manage system'

In [10]: "Welcome to manage system".center(40,"*")
Out[10]: '********Welcome to manage system********'


str.count(sub[, start[, end]]) -> int - 返回sub在str中出现的次数,如果start与end指定,则返回指定范围内的sub出现次数。
In [14]: "qqsdcsdcsc".count("s",1,6)  ##1 6 表示指定位置
Out[14]: 2


str.endswith(suffix[, start[, end]]) - 判断字符串是否以suffix结束,如果start和end指定,则返回str中指定范围内str子串是否以suffix结尾,如果是,返回True;否则返回False
str.startswith(prefix[, start[, end]])
In [18]: a.endswith("s")  ##判断 a是否以s结尾
Out[18]: True
 
In [19]: a.startswith("s")  ##判断a是否以s开头
Out[19]: False


str.find(sub[,start[,end]]) - 判断sub是否在str中,存在返回索引值,不存在返回-1,存在则返回位置.
In [20]: a.find("a")
Out[20]: -1

In [21]: a.find("s")
Out[21]: 2

In [22]: a.find("w")
Out[22]: 0

In [23]: a.find("e")
Out[23]: 1


str.index(sub[,start[,end]]) - 与find方法函数功能相同,如果sub不存在时抛出ValueError异常
In [27]: a.index("a")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-c06edcd15603> in <module>()
----> 1 a.index("a")

ValueError: substring not found   ##ValueError异常


str.isalnum() //判断是否都是字母或数字
In [29]: "ac45vd".isalnum()
Out[29]: True

In [30]: "#ac45vd".isalnum()
Out[30]: False

str.isalpha() //判断是否都是字母
In [32]: "sssfsd".isalpha()
Out[32]: True

In [33]: "2sssfsd".isalpha()
Out[33]: False

str.isdigit() //判断是否都是数字
In [34]: "21313".isdigit()
Out[34]: True

In [35]: "21313d".isdigit()
Out[35]: False

str.islower() //判断是否都是小写
In [36]: "asd".islower()
Out[36]: True

In [37]: "asdS".islower()
Out[37]: False

str.isspace()  //判断是否都是英文空格
str.istitle()  //判断是不是都是标题(有大小写)
str.isupper()  //判断是不是都为大写字母
str.join(seq)  //- 以str作为分隔符,将序列seq中的所有元素合并为一个新的字符串。
In [39]: "b".join("asddgf")
Out[39]: 'absbdbdbgbf'

str.replace(old,new[,count])- 将str中的old字符串替换为new字符串,并将替换后的新字符串返回,如果count指定,则只替换前count个字符串
In [40]: "aaaaaav".replace("a","b",4)
Out[40]: 'bbbbaav'


str.split([sep[,maxsplit]]) //- 以sep字符串作为分割符对str进行切割,默认为空格;- maxsplit代表切割的次数
In [41]: "aaahddddhdsdh".split("h")
Out[41]: ['aaa', 'dddd', 'dsd', '']

In [42]: "aaahddddhdsdh".split("h",2)
Out[42]: ['aaa', 'dddd', 'dsdh']

str.strip([chars])  //- 返回一字符串,将str中首尾包含指定的chars字符删除的字符串,未指定时,删除首尾的空格。
In [43]: "  hello   ".strip()
Out[43]: 'hello'

In [44]: "helloh".strip("h")
Out[44]: 'ello'

str(obj)   将其他类型内容转换为字符串
int(obj)   将字符串转换为为整数
float(obj) 将字符串转换为浮点型
long(obj)  将字符串转换为长整型


练习:写一个脚本检测变量名是否合法

import string
a = string.letters + '_'
b = string.digits
print "welcome to test system".center(40,'*')

testname = raw_input("输入需要检测的变量名:")
if testname[0] not in a :
   print "the testname has a wrong begin"
   exit(1)
else:
    for d in testname[1:]:
        if d not in a + b:
           print "the testname is wrong"
           exit(1)
print "the testname is ok"
exit(1)









原创粉丝点击