(董付国)Python 学习笔记---Python字符串与正则表达式(1)

本文介绍了Python 3中字符串的基本操作,包括编码格式、字符串不可变性、常用方法如find、split、replace以及字符串格式化的新方法。还提及了字符串连接的最佳实践和字符串加密的基本概念。
摘要由CSDN通过智能技术生成

第四章 字符串与正则表达式

  • 最早的字符串编码是美国的标准信息交换码ASCII。随着信息技术的发展和信息交换的需要,各国的文字都需要进行编码,不同的应用领域和场合对字符串编码的要求也略有不同,常见的有UTF-8、UTF-16、UTF-32、GB2312(我国)、GBK、CP936、CP437等等。
  • 不同编码格式之间相差很大,采用不同的编码格式意味着不同的表示和存储形式,把同一字符存入文件时,写入的内容可能会不同,在试图理解其内容时必须了解编码规则并进行正确的解码。如果解码方法不正确就无法还原信息,从这个角度来讲,字符串编码也具有加密效果
  • Python 3.X完全支持中文字符,默认使用UTF8编码格式,无论是一个数字、一个英文字母,还是一个汉字,都按一个字符对待和
    处理。
  • 在Python中,字符串属于不可变序列类型,除了支持序列通用方法(包括切片操作)以外,还支持特有的字符串操作方法,反向索引等操作。
  • Python字符串驻留机制:对于短字符串,将其赋值给多个不同对象时,内存中只有一个副本,就是一个短字符串可以同时对应多个不同变量,多个对象共享该副本。但是长字符串不遵守驻留机制,即当字符串比较长时,把它赋给多个变量是,内存中是有多个不同地址存储它的。

4.1.1 字符串格式化
在这里插入图片描述

  • 常用格式字符
    在这里插入图片描述
>>> x = 1235
>>> so = "%o" % x
>>> so
'2323'
>>> sh = "%x" % x
>>> sh
'4d3'
>>> se = "%e" % x
>>> se
'1.235000e+03'
>>> chr(ord("3")+1)
'4'
>>> "%s" % 65
'65'
>>> "%s" % 65333
'65333'
>>> "%d" % "555"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> int('555')
555
>>> '%s' %[1,2,3]
'[1, 2, 3]'
>>> str((1,2,3))
'(1, 2, 3)'
>>> str([1,2,3])
'[1, 2, 3]'
  • 使用format方法进行格式化
>>> print("The number {0:,} in hex is : {0:#x}, the number {1} in oct is {1:#o}".format(5555,55))
The number 5,555 in hex is : 0x15b3, the number 55 in oct is 0o67
>>> print("The number {1:,} in hex is : {1:#x}, the number {0} in oct is {0:#o}".format(5555,55))
The number 55 in hex is : 0x37, the number 5555 in oct is 0o12663
>>> print("my name is {name},my age is {age}, and my QQ is {qq}".format(name = "He Zhibin",age = 22,qq = "30647355"))
my name is He Zhibin,my age is 22, and my QQ is 30647355
>>> position = (5,8,13)
>>> print("X:{0[0]};Y:{0[1]};Z:{0[2]}".format(position))
X:5;Y:8;Z:13
>>> weather = [("Monday","rain"),("Tuesday","sunny"),("Wednesday","sunny"),("Thursday","rain"),("Friday","Cloudy")]
>>> formatter = "Weather of '{0[0]}' is '{0[1]}'".format
>>> for item in map(formatter,weather):
...     print(item)
...
Weather of 'Monday' is 'rain'
Weather of 'Tuesday' is 'sunny'
Weather of 'Wednesday' is 'sunny'
Weather of 'Thursday' is 'rain'
Weather of 'Friday' is 'Cloudy'
>>> for item in weather:
...     print(formatter(item))
...
Weather of 'Monday' is 'rain'
Weather of 'Tuesday' is 'sunny'
Weather of 'Wedn
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值