三木社区

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 530|回复: 0
打印 上一主题 下一主题

python基础-字符串

[复制链接]

1562

主题

1564

帖子

4904

积分

博士

Rank: 8Rank: 8

积分
4904
跳转到指定楼层
楼主
发表于 2017-9-5 11:23:40 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 blake 于 2017-9-5 11:28 编辑

Python 3 的源码的默认编码方式为 UTF-8

python 3,所有的字符串都是使用Unicode编码的字符序列。

utf-8 是一种将字符编码成字节序列的方式。字节即字节,并非字符。字符在计算机内只是一种抽象。字符串则是一种抽象的序列。在这里我们只讨论字符串,不讨论字节。


在Python 中,字符串可以用单引号括起来,也可以用双引号,甚至是三引号。

但如果字符串中含有单引号,你应该用双引号来括,或者用转义符加单引号括起来。含有双引号的同理。

三引号的字符串可以换行!

  1. >>> 'Let's go!'  
  2. SyntaxError: invalid syntax  
  3. >>> "Let's go!"  
  4. "Let's go!"  
  5. >>> 'Let\'s go!'  
  6. "Let's go!"  
  7. >>> '''''begin
  8. and
  9. next
  10. end'''  
  11. 'begin\nand\nnext\nend'
复制代码
字符串是不可修改的,这点很重要!你可以把它想象为字符组成的元组。
  1. >>> s = "HelloWorld"  
  2. >>> s[0] = 'h'  
  3. Traceback (most recent call last):  
  4.   File "<pyshell#123>", line 1, in <module>  
  5.     s[0] = 'h'  
  6. TypeError: 'str' object does not support item assignment  
复制代码
如果你想修改它,可以先转换成列表,修改完成后再转为字符串。
  1. >>> s  
  2. 'HelloWorld'  
  3. >>> L = list(s)  
  4. >>> L  
  5. ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']  
  6. >>> L[0] = 'h'  
  7. >>> ''.join(L) #这是什么?别着急,下面我们会谈到  
  8. 'helloWorld'  
复制代码
字符串可以进行直接拼接,但如果是两个变量代表的字符串,你还是用 + 号吧
  1. >>> s = "Hello""World"  
  2. >>> s  
  3. 'HelloWorld'  
  4. >>> s1 = "Hello"  
  5. >>> s2 = "World"  
  6. >>> s1s2  
  7. Traceback (most recent call last):  
  8.   File "<pyshell#138>", line 1, in <module>  
  9.     s1s2  
  10. NameError: name 's1s2' is not defined  
  11. >>> s1+s2  
  12. 'HelloWorld'  
复制代码
字符串操作和方法:

len(s)  返回字符串长度

x in s 查询 x 是否在 s 中

  1. >>> s = "HelloWorld"  
  2. >>> len(s)  
  3. 10  
  4. >>> "ll" in s  
  5. True  
复制代码
s.find( x )  在字符串 s 中找子串 x ,找到则返回最左端的索引,找不到则返回-1
  1. >>> s  
  2. 'HelloWorld'  
  3. >>> s.find("l")  
  4. 2  
  5. >>> s.find('w')  
  6. -1  
复制代码

s.splitlines() 将多行字符串分割成多个单行字符串组成的列表,换行符被吸收


  1. >>> s = '''''begin
  2. ...then..
  3. ...next..
  4. end...'''  
  5. >>> s.splitlines()  
  6. ['begin', '...then..', '...next..', 'end...']  
复制代码
s.split( x ) 以 x 作为分隔符将 s 分割成一个字符串列表,如果不提供x,则程序会自动将所有空格和换行作为分隔符分割

  1. >>> s = "here#there"  
  2. >>> s.split('#') # #作为分隔符  
  3. ['here', 'there']  
  4. >>> s = '''''begin
  5. .then.. and
  6. .next.
  7. end'''  
  8. >>> s.split()  #默认情况将所有换行和空格都分割  
  9. ['begin', '.then..', 'and', '.next.', 'end']  
复制代码

[size=18.018px]s.lower()   返回s 的小写形式的字符串

[size=18.018px]s.upper() 返回 s 的大写形式的字符串

  1. >>> s = 'HelloWorld'  
  2. >>> s.lower()  
  3. 'helloworld'  
  4. >>> s.upper()  
  5. 'HELLOWORLD'
复制代码
[size=18.018px]s.join( seq )  split 的逆方法,将序列 seq 用 s 连接起来,必须是字符串序列
  1. >>> L = ['1','33','42']  
  2. >>> '+'.join(L)  #用+来连接  
  3. '1+33+42'  
  4. >>> L = list(s) #拆开s  
  5. >>> L  
  6. ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']  
  7. >>> ''.join(L)  #粘合了。。。  
  8. 'HelloWorld'  
复制代码
[size=18.018px]s.replace( x, y)  将 s 中所有匹配 x 的项用 y 代替,如果找不到,那就直接返回 s 咯
  1. >>> s  
  2. 'HelloWorld'  
  3. >>> s.replace("World","Cheng")  
  4. 'HelloCheng'  
  5. >>> s.replace("world","Cheng") #知道为什么吧...  
  6. 'HelloWorld'  
复制代码
[size=18.018px]s.strip( x ) 如果不提供 x,那么返回去除了首尾两侧空格的字符串,如果提供了字符串 x,那么将去除s首尾所有在 x 中的字符并返回
  1. >>> s = "   Hi,I'm Alice!   "  
  2. >>> s.strip()  
  3. "Hi,I'm Alice!"  
  4. >>> s.strip("! ")  #这是两个字符哦  
  5. "Hi,I'm Alice" #少了一个感叹号哦!  
复制代码

[size=18.018px]再次注意:以上方法都没有改变原字符串,字符串是不可改变的!


[size=18.018px]以下简单看看:

[size=18.018px]s.starstwith( x )  测试 s 是否以 x 开头

[size=18.018px]s.endswith( x )  测试 s 是否以 x 结尾

[size=18.018px]s.isalnum()  测试 s 是否全是字母和数字,并至少有一个字符

[size=18.018px]s.isalpha()   测试 s 是否全是字母,并至少有一个字符

[size=18.018px]s.isdigit()  测试 s 是否全是数字,并至少有一个字符

[size=18.018px]s.isspace()  测试 s 是否全是空白字符,并至少有一个字符

[size=18.018px]s.islower() 测试 s 中的字母是否全是小写

[size=18.018px]s.isupper() 测试 s 中的字母是否便是大写

[size=18.018px]s.istitle() 测试 s 是否是首字母大写的


[size=18.018px]让我们重点关注一个强大的格式化方法 format ,看下面代码

  1. >>> name = 'Jonh'  
  2. >>> call = '13560300xxx'  
  3. >>> "{0}'s telephone number is {1}".format(name,call) # (1)  
  4. "Jonh's telephone number is 13560300xxx"  
  5. >>> addr = "A103"  
  6. >>> "{0}'s telephone number is {1} and his address is {2}".format(name,call,addr) #(2)  
  7. "Jonh's telephone number is 13560300xxx and his address is A103"  
复制代码

[size=18.018px](1)句中,字符串中 {0} 被 format 的第一个参数代替,{1} 被第二个参数代替。两个参数不够?事实上,你可以给予它任意多个参数,然后用相同个数的替换字段进行替换。什么是替换字段?{0},{1}就叫做替换字段。我们在第(2)句中使用了3个替换字段,{0}对应name, {1}对应call,{2}对应addr。再多的参数也类似于刚才的做法。


[size=18.018px]那么,仅仅是这样?当然不是!让我们继续看

  1. >>> L = [2,3,5,7]  
  2. >>> print("x is {0[0]}, y is {0[2]}".format(L))  
  3. x is 2, y is 5  
复制代码

[size=18.018px]{0[0]} 表示L[0],{0[2]} 表示L[2],它们叫做复合字段名[size=18.018px],你可以:

[size=18.018px](1)使用列表作为参数,并且通过下标索引来访问其元素(跟上一例类似)

[size=18.018px](2)使用字典作为参数,并且通过键来访问其值

  1. >>> d  
  2. {'b': 2, 'a': 1}  
  3. >>> print("x is {0[a]}, y is {0[b]}".format(d))  
  4. x is 1, y is 2  
  5. >>> d = {2:3.5,7:4.5}  
  6. >>> print("x is {0[2]}, y is {0[7]}".format(d))  
  7. x is 3.5, y is 4.5  
复制代码

[size=18.018px]d 为字典,a 、b为键,{0[a]} 对应到了值2(注意:是a,b,不是'a', 'b')


[size=18.018px](3)使用模块作为参数,并且通过名字来访问其变量及函数

  1. >>> print("{0.random}".format(random))  
  2. <built-in method random of Random object at 0x022D61F8>  
复制代码
[size=18.018px]4)使用类的实例[size=18.018px]作为参数,并且通过名字来访问其方法和属性
  1. >>> class A:  
  2.     pass  
  3.   
  4. >>> x = A()  
  5. >>> print("The class is {0.__class__}".format(x))  
  6. The class is <class '__main__.A'>  
复制代码

[size=18.018px]5)以上方法的任意组合


[size=18.018px]替换字段除了整数,你还可以使用参数名字

  1. >>> print("{name}'s telephone number is {call}".format(name = "Jonh",call = 69993))  
  2. Jonh's telephone number is 69993  
复制代码
[size=18.018px]在替换域中,你还可以使用格式说明符[size=18.018px]。冒号 : 标示格式说明符的开始。
  1. >>> pi = 3.141592653  
  2. >>> print("The pi is {0:10.3f}".format(pi)) # 0:10.3f 表示输出宽度为10,保留三位小数,浮点数  
  3. The pi is      3.142  
复制代码

回复

使用道具 举报

Archiver|手机版|小黑屋|三木电子社区 ( 辽ICP备11000133号-4 )

辽公网安备 21021702000620号

GMT+8, 2025-10-24 00:20 , Processed in 0.026999 second(s), 22 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表