首页 > 代码库 > Python 字符串 : part 1

Python 字符串 : part 1

Python 字符串 : part 1

                                  ----字符串:有序地字符的集合

1、单引号和双引号字符串是一样的,单引号中嵌入双引号或双引号中嵌入单引号没问题,单引号嵌入单引号或双引号嵌入双引号报错,需用转义字符。#报错信息:SyntaxError: invalid syntax(语法错误:无效的语法)

2、常用转义字符:\n 换行 ; \t 制表键(2字节) ; \a 响铃 ; \0 <--这个是零 Null 

3、转义字符后面的内容无意义时,转义字符保留原写法留在变量中。

4、三引号代表的是块字符串。<但很多时候是用来将多行代码注释掉>

5、字符串可通过 + 来合并,通过 * 来进行重复,通过 len() 求长度。

In [44]: len(abc)
Out[44]: 3

In [45]: abc+cde
Out[45]: abccde

In [46]: Hello*6
Out[46]: HelloHelloHelloHelloHelloHello

In [47]: -*80
Out[47]: --------------------------------------------------------------------------------

In [48]: print(-*80)
--------------------------------------------------------------------------------

In [49]: myjob=doctor

In [50]: for i in myjob:
    ...:     print(i,end= )
d o c t o r

In [53]: o in myjob
Out[53]: True

In [55]: ob in myjob
Out[55]: False

In [56]: ob in "obb"
Out[56]: True

6、Python的索引值以 0 开始,最大值为字符串长度减 1 。分片最右边的数值不包含右边界。分片的第三限制值为步进,负数表示从右向左,同时左右边界反转。

In [74]: s=abcdefghijklmnopqrstuvwxyz

In [75]: s
Out[75]: abcdefghijklmnopqrstuvwxyz

In [76]: s[1:10]
Out[76]: bcdefghij

In [77]: s[1:]
Out[77]: bcdefghijklmnopqrstuvwxyz

In [78]: s[:10]
Out[78]: abcdefghij

In [79]: s[:-1]
Out[79]: abcdefghijklmnopqrstuvwxy

In [80]: s[1:25:2]
Out[80]: bdfhjlnprtvx

In [81]: s[::2]
Out[81]: acegikmoqsuwy

In [82]: s[::-1]
Out[82]: zyxwvutsrqponmlkjihgfedcba

In [83]: s[8:4:-2]
Out[83]: ig

7、字符串转换工具:int()转换为整数; str()转换为字符串; repr()转换为字符串; float()转换为浮点; ord() 转换为对应的ASCII码值; chr()为ord的反向操作。

#二进制换算为10进制
In [94]: B=1101

In [95]: I=0

In [97]: while B!=‘‘:
    ...:     I=I*2+(ord(B[0])-ord(0))
    ...:     B=B[1:]
    ...:

In [98]: I
Out[98]: 13

8、修改字符串不能在原地修改,可采用合并的方法或 .replace方法。附格式化输出例子:

In [102]: S=abc

In [103]: S
Out[103]: abc

In [104]: S[0]
Out[104]: a

In [105]: S[0]=b
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-105-47eb3968d8a6> in <module>()
----> 1 S[0]=b

TypeError: str object does not support item assignment
In [106]: S=S[:4]+BBB

In [107]: S
Out[107]: abcBBB

In [108]: S.replace(BBB,CCC)
Out[108]: abcCCC
In [110]: name=dereck

In [111]: age=30

In [112]: city=Tianjin

In [114]: print(Hello everyone,I am %s,I am %d years old, I comes from %s %(name,age,city))
Hello everyone,I am dereck,I am 30 years old, I comes from Tianjin

 

====== The End ======

Python 字符串 : part 1