python之字符串

字符串与文本操作

字符串:

  • Python 2和Python 3最大的差别就在于字符串
  • Python 2中字符串是byte的有序序列
  • Python 3中字符串是unicode的有序序列
  • 字符串是不可变的
  • 字符串支持下标与切片
# 证明字符串支持切片和下标
In [40]: s = ‘hello world!‘

In [41]: s[0]
Out[41]: ‘h‘

In [42]: s[0:3]
Out[42]: ‘hel‘

In [43]: s[::-1]
Out[43]: ‘!dlrow olleh‘

# 证明字符串是不可变类型
In [44]: s[0] = ‘L‘
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-887f788ca844> in <module>()
----> 1 s[0] = ‘L‘

TypeError: ‘str‘ object does not support item assignment

字符串格式化(两种方式)

  • Python字符串支持两种方式格式化
  • print style format
  • format方法

print style format

template % tuple (1)
template % dict (2)
template 为带有一些标记的字符串,使用 tuple 中的元素一次填充
template 为带有一些标记的字符串,使用 dict 中的values按key填充

template 的一般格式:

% (key) flag conversion (1) (2) (3) (4)
% 开始

1.可选的 (key) 如果指定了key, 将从字典中获取对应的value, 否则根据位置从元组中获取
2.可选的 flag
3.必选的 conversion

实例:

In [45]: ‘I love %s‘ % (‘Python‘, )
Out[45]: ‘I love Python‘

In [46]: ‘I love %(name)s‘ % {‘name‘: ‘Python‘}
Out[46]: ‘I love Python‘

In [47]: ‘I love %s, %s is my first lang‘ % (‘Python‘, ‘PY‘)
Out[47]: ‘I love Python, PY is my first lang‘

flag

Flag 说明 实例

#


此处 # 代表一个数字,指定宽度,如果宽度不够,会更具以下的规则填充


‘%3s‘ % (‘a‘, ) → ‘••a‘


0


使用0填充,仅适用于数字


‘%03d‘ % (1,) → ‘001‘



使用空格填充,默认行为


’%•3d‘ % (1,) ` → ‘••1‘

flag

Flag 说明 实例

-


右边使用空格填充


‘%-3d‘ % (1,) → ‘1••‘


+


填充之前增加`+` 仅对于正数


‘%+03d‘ % (1, ) → ‘+01‘

Conversion

符号 说明 符号 说明

d


整数


i


整数


o


八进制整数


u


整数,已废弃


x


小写十六进制整数


X


大写十六进制整数


f


浮点数


F


浮点数


e


小写科学计数法


E


大写科学计数法

Conversion

符号 说明 符号 说明

g


同f, 如果指数小于-4,同e


G


同f, 如果指数小于-4,同E


c


字符,接收unicode编码或单字符字符串


a


字符串,使用 ascii 函数转换


r


字符串,使用 repr 函数转换

format函数

template.format(*args, **kwargs) (1) (2) (3) (4)
  1. template 使用 {} 标示变量
  2. {} 或 {\d+} 使用 *args 按顺序填充
  3. {key} 使用 **kwargs 按key填充
  4. Format String Syntax
In [48]: d = {‘a‘:1, ‘b‘: 2, ‘c‘:3}

In [49]: for k,v in d.items():
   ....:     print(‘key/value : {0} ==> {1}‘.format(k,v))
   ....:
key/value : b ==> 2
key/value : a ==> 1
key/value : c ==> 3

字符串常用操作

  • 字符串连接 join
In [50]: lista =[‘I‘, ‘love‘, ‘Python‘]

In [51]: ‘ ‘.join(lista)
Out[51]: ‘I love Python‘
  • 字符串分割 splitrsplitsplitlinespartitionrpartition
In [53]: s.split(‘:‘,1)
Out[53]: [‘root‘, ‘x:0:0:root:/root:/bin/bash‘]
  • 字符串修改-大小写 capitalizetitlelowerupperswapcase
# 此行第一个首字母大写
In [58]: s.capitalize()
Out[58]: ‘I love python‘
# 每个单词的首字母大写
In [59]: s.title()
Out[59]: ‘I Love Python‘
# 全部转化为小写
In [60]: s.lower()
Out[60]: ‘i love python‘
# 全部转化为大写
In [61]: s.upper()
Out[61]: ‘I LOVE PYTHON
# 大小写互换
In [63]: s = ‘i Love Python‘
In [64]: s.swapcase()
Out[64]: ‘I lOVE pYTHON‘
  • 字符串修改-填充清除 centerljustrjustzfillstriprstriplstrip
# center 填充,一般用在格式化输出
In [65]: s = ‘Python‘
In [67]: s.center(20,‘-‘)
Out[67]: ‘-------Python-------‘

# 去掉换行符strip()
In [68]: s = ‘abc\n‘

In [69]: s.strip()
Out[69]: ‘abc‘
  • 字符串判断 startswithendswithis*
In [81]: s = ‘abcdefg‘
# 字符串是以a开头
In [83]: s.startswith(‘a‘)
Out[83]: True

In [84]: if s.startswith(‘a‘):
   ....:     print(‘ok‘)
   ....:
ok
# 是以g为结尾的.
In [85]: if s.endswith(‘g‘):
    print(‘ok‘)
   ....:
ok
  • 字符串查找替换 countfindrfindindexrindex,replace
s = ‘root:x:0:0:root:/root:/bin/bash\n‘
# count统计个数
In [103] : s.count(‘root‘)
Out[103] : 3
In [87]: s = ‘root:x:0:0:root:/root:/bin/bash\n‘

# replace进行替换,可以指定替换次数.
In [88]:  s.replace(‘root‘, ‘admin‘, 1)
Out[88]: ‘admin:x:0:0:root:/root:/bin/bash\n‘

str与bytes

  • Python3中严格区分了文本和二进制数据
  • Python2并没有严格区分
  • 文本数据使用str类型,底层实现是unicode
  • 二进制数据使用bytes类型,底层是byte
  • str使用encode方法转化为bytes
  • bytes方法使用decode方法转化为str
  • 由于清晰的区分文本和二进制,Python3解决了大多数Python2的编码问题
时间: 2024-08-06 07:55:38

python之字符串的相关文章

Python 的字符串类子串查找函数

Python 的字符串类有个很好用的函数,可很方便的用于与查找Python字符串类型对象子串相关的操作,具体的API如下: | find(...) | S.find(sub [,start [,end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within s[start:end]. Optional | arguments start

python中字符串链接的七种方式

一. str1+str2 string类型 '+'号连接 >>> str1="one" >>> str2="two" >>> str1+str2 'onetwo' >>>注意:该方式性能较差,因为python中字符串是不可变的类型,使用 + 连接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当连续相加的字符串很多时(a+b+c+d+e+f+...) ,效率低下就是必然的了例

Python格式化字符串

在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作符,非常类似C语言里的printf()函数的字符串格式化(C语言中也是使用%). 下面整理了一下Python中字符串格式化符合: 格式化符号 说明 %c 转换成字符(ASCII 码值,或者长度为一的字符串) %r 优先用repr()函数进行字符串转换 %s 优先用str()函数进行字符串转换 %d / %i 转成有符号十进制数 %u

Python中字符串查找效率比较

Python中字符串查找方式有多种,常见的有re.match/search or str.find 用一个例子来说明各种方式的效率如下: from timeit import timeit import re def find(string, text): if string.find(text) > -1: pass def re_find(string, text): if re.match(text, string): pass def best_find(string, text): i

Python格式化字符串~转

Python格式化字符串 在编写程序的过程中,经常需要进行格式化输出,每次用每次查.干脆就在这里整理一下,以便索引. 格式化操作符(%) "%"是Python风格的字符串格式化操作符,非常类似C语言里的printf()函数的字符串格式化(C语言中也是使用%). 下面整理了一下Python中字符串格式化符合: 格式化符号 说明 %c 转换成字符(ASCII 码值,或者长度为一的字符串) %r 优先用repr()函数进行字符串转换 %s 优先用str()函数进行字符串转换 %d / %i

python连接字符串的方式

发现Python连接字符串又是用的不顺手,影响速度 1.数字对字符进行拼接 s=""  #定义这个字符串,方便做连接 print type(s) for i in range(10): print i type(i) s+=str(i)  #转换类型在对接 print s 2.字符对字符进行拼接 string="abcdef" for i in string: print i+'jun'  直接使用字符串连接 3.列表和字符串的拼接 list1=['hello','

以写代学:python 原始字符串操作符&&字符串内建函数

原始字符串操作符 (1)原始字符串操作符是为了对付那些在字符串中出现的特殊字符 (2)在原始字符串里,所有的字符都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符 (3)比如在windows写路径时经常会把出现以下情况 2.字符串内建函数 (1)每次都不会改变字符串原本的值 (2)字符串.函数 或者将字符串赋值给函数后写成变量名.函数是都可以的 (3)还有很多的内涵函数,下边只是举例说明 >>> import tab        >>> hi = "

python 之字符串和编码

字符编码 我们已经讲过了,字符串也是一种数据类型,但是,字符串比较特殊的是还有一个编码问题. 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用8个比特(bit)作为一个字节(byte),所以,一个字节能表示的最大的整数就是255(二进制11111111=十进制255),如果要表示更大的整数,就必须用更多的字节.比如两个字节可以表示的最大整数是65535,4个字节可以表示的最大整数是4294967295. 由于计算机是美国人发明的,因此,最早只有1

Python基础-字符串格式化_百分号方式_format方式

Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator. 1.百分号

Python格式化字符串的替代符与转义字符

                                               Python格式化字符串的替代符以及含义     符   号     说     明       %c  格式化字符及其ASCII码       %s  格式化字符串       %d  格式化整数       %u  格式化无符号整型       %o  格式化无符号八进制数       %x  格式化无符号十六进制数       %X  格式化无符号十六进制数(大写)       %f  格式化浮点