【python】字符串(String)详解 及 代码,全网最全总结

字符串编码

必须要了解的两种编码方式:

  • UTF-8:对全世界所有国家需要用到的字符进行了编码,以1个字节表示英语字符(兼容ASCII),以3个字节表示中文,还有些语言的符号使用2个字节(例如俄语和希腊语符号)或4个字节。
  • GB2312:是我国制定的中文编码,使用1个字节表示英语,2个字节表示中文;GBK是GB2312的扩充,而CP936是微软在GBK基础上开发的编码方式。GB2312、GBK和CP936都是使用2个字节表示中文。


一、字符串介绍

1、Python 3.x完全支持中文字符,默认使用UTF8编码格式,无论是一个数字、英文字母,还是一个汉字,都按一个字符对待和处理。

>>> s = '中国河南郑州'
>>> len(s)                  #字符串长度,或者包含的字符个数
6
>>> s = '中国河南郑州ABCDE'  #中文与英文字符同样对待,都算一个字符
>>> len(s)
11
>>> 姓名 = '李四'            #使用中文作为变量名
>>> print(姓名)              #输出变量的值
李四

2、在Python中,字符串属于不可变序列类型,除了支持序列通用方法(包括分片操作)以外,还支持特有的字符串操作方法。

>>> text='hello world'
>>> id(text)
1620515787760
>>> text[0]='k'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> text='well'
>>> id(text)
1620515761600
>>>

3、Python字符串驻留机制:对于短字符串,将其赋值给多个不同的对象时,内存中只有一个副本,多个对象共享该副本。长字符串不遵守驻留机制。

二、字符串格式化

1.常用格式字符

格式字符说明
%s字符串 (采用str()的显示)
%r字符串 (采用repr()的显示)
%c单个字符
%b二进制整数
%d十进制整数
%i十进制整数
%o八进制整数
%x十六进制整数
%e指数 (基底写为e)
%E指数 (基底写为E)
%f、%F浮点数
%g指数(e)或浮点数 (根据显示长度)
%G指数(E)或浮点数 (根据显示长度)
%c%字符"%""%"
>>> 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"
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]'

2.使用format方法

print("The number {0:,} in hex is: {0:#x}, the number {1} in oct is {1:#o}".format(5555,55))
print("The number {1:,} in hex is: {1:#x}, the number {0} in oct is {0:#o}".format(5555,55))
print("my name is {name}, my age is {age}, and my QQ is {qq}".format(name = "Dong Fuguo",age = 37,qq = "306467355"))
position = (5,8,13)
print("X:{0[0]};Y:{0[1]};Z:{0[2]}".format(position))

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)
for item in weather:
    print(formatter(item))

三、 字符串常用方法

1、find( )、rfind()、index()、rindex()、count()

  • find()和rfind方法分别用来查找一个字符串在另一个字符串指定范围(默认是整个字符串)中首次和最后一次出现的位置,如果不存在则返回-1;
  • index()和rindex()方法用来返回一个字符串在另一个字符串指定范围中首次和最后一次出现的位置,如果不存在则抛出异常;
  • count()方法用来返回一个字符串在另一个字符串中出现的次数。

2、split()、rsplit()、partition()、rpartition()

  • split()和rsplit()方法分别用来以指定字符为分隔符,将字符串左端和右端开始将其分割成多个字符串,并返回包含分割结果的列表;
  • partition()和rpartition()用来以指定字符串为分隔符将原字符串分割为3部分,即分隔符前的字符串、分隔符字符串、分隔符后的字符串,如果指定的分隔符不在原字符串中,则返回原字符串和两个空字符串。
>>> s="apple,peach,banana,pear"
>>> li=s.split(",")
>>> li
["apple", "peach", "banana", "pear"]
>>> s.partition(',')
('apple', ',', 'peach,banana,pear')
>>> s.rpartition(',')
('apple,peach,banana', ',', 'pear')
>>> s.rpartition('banana')
('apple,peach,', 'banana', ',pear')
>>>s = "2014-10-31"
>>> t=s.split("-")
>>> print(t)
['2014', '10', '31']
>>> print(list(map(int, t)))
[2014, 10, 31]

对于split()和rsplit()方法,如果不指定分隔符,则字符串中的任何空白符号(包括空格、换行符、制表符等等)都将被认为是分隔符,返回包含最终分割结果的列表。
split()和rsplit()方法还允许指定最大分割次数,这里不一一列举代码。

3、join()

>>> li=["apple", "peach", "banana", "pear"]
>>> sep=","
>>> s=sep.join(li)
>>> s
"apple,peach,banana,pear"

4、lower()、upper()、capitalize()、title()、swapcase()

>>> s = "What is Your Name?"
>>> s.lower()                   #返回小写字符串
'what is your name?'
>>> s.upper()                   #返回大写字符串
'WHAT IS YOUR NAME?'
>>> s.capitalize()              #字符串首字符大写
'What is your name?'
>>> s.title()                   #每个单词的首字母大写
'What Is Your Name?'
>>> s.swapcase()                #大小写互换
'wHAT IS yOUR nAME?'

5、replace()

查找替换replace(),类似于“查找与替换”功能

测试题:用户输入中是否有敏感词,如果有的话就把敏感词替换为3个星号***。

>>> words = ('测试', '非法', '暴力', '话')
>>> text = '这句话里含有非法内容'
>>> for word in words:
	if word in text:
		text = text.replace(word, '***')		
>>> text
'这句***里含有***内容'

6、maketrans()

字符串对象的maketrans()方法用来生成字符映射表,而translate()方法用来根据映射表中定义的对应关系转换字符串并替换其中的字符,使用这两个方法的组合可以同时处理多个不同的字符,replace()方法则无法满足这一要求。

#创建映射表,将字符"abcdef123"一一对应地转换为"uvwxyz@#$"
>>> table = ''.maketrans('abcdef123', 'uvwxyz@#$')
>>> s = "Python is a greate programming language. I like it!"
#按映射表进行替换
>>> s.translate(table)
'Python is u gryuty progrumming lunguugy. I liky it!'

7、凯撒加密

>>> import string
>>> def kaisa(s, k):
	lower = string.ascii_lowercase          #小写字母
	upper = string.ascii_uppercase          #大写字母
	before = string.ascii_letters
	after = lower[k:] + lower[:k] + upper[k:] + upper[:k]
	table = ''.maketrans(before, after)     #创建映射表
	return s.translate(table)

>>> s = "Python is a greate programming language. I like it!"
>>> kaisa(s, 3)
'Sbwkrq lv d juhdwh surjudpplqj odqjxdjh. L olnh lw!'

8、strip()、rstrip()、lstrip()

>>> s = " abc  "
>>> s2 = s.strip()                        #删除空白字符
>>> s2
"abc"
>>> '\n\nhello world   \n\n'.strip()      #删除空白字符
'hello world'
>>> "aaaassddf".strip("a")                #删除指定字符
"ssddf"
>>> "aaaassddf".strip("af")
"ssdd"
>>> "aaaassddfaaa".rstrip("a")            #删除字符串右端指定字符
'aaaassddf'
>>> "aaaassddfaaa".lstrip("a")            #删除字符串左端指定字符
'ssddfaaa'

这三个函数的参数指定的字符串并不作为一个整体对待,而是在原字符串的两侧、右侧、左侧删除参数字符串中包含的所有字符,一层一层地从外往里扒。

>>> 'aabbccddeeeffg'.strip('af')  #字母f不在字符串两侧,所以不删除
'bbccddeeeffg'
>>> 'aabbccddeeeffg'.strip('gaf')
'bbccddeee'
>>> 'aabbccddeeeffg'.strip('gaef')
'bbccdd'
>>> 'aabbccddeeeffg'.strip('gbaef')
'ccdd'
>>> 'aabbccddeeeffg'.strip('gbaefcd')
''

9、startswith()、endswith()

判断字符串是否以指定字符串开始或结束

>>> s = 'Beautiful is better than ugly.'
>>> s.startswith('Be')             #检测整个字符串
True
>>> s.startswith('Be', 5)         #指定检测范围起始位置
False
>>> s.startswith('Be', 0, 5)     #指定检测范围起始和结束位置
True
>>> import os
>>> [filename for filename in os.listdir(r'c:\\') if filename.endswith(('.bmp','.jpg','.gif'))]

10、center()、ljust()、rjust()

返回指定宽度的新字符串,原字符串居中、左对齐或右对齐出现在新字符串中,如果指定宽度大于字符串长度,则使用指定的字符(默认为空格)进行填充。

>>> 'Hello world!'.center(20)        #居中对齐,以空格进行填充
'    Hello world!    '
>>> 'Hello world!'.center(20, '=')   #居中对齐,以字符=进行填充
'====Hello world!===='
>>> 'Hello world!'.ljust(20, '=')    #左对齐
'Hello world!========'
>>> 'Hello world!'.rjust(20, '=')    #右对齐
'========Hello world!'

11、isalnum()、isalpha()、isdigit()、isdecimal()、isnumeric()、isspace()、isupper()、islower()

isalnum()、isalpha()、isdigit()、isdecimal()、isnumeric()、isspace()、isupper()、islower(),用来测试字符串是否为数字或字母、是否为字母、是否为数字字符、是否为空白字符、是否为大写字母以及是否为小写字母。

>>> '1234abcd'.isalnum()
True
>>> '1234abcd'.isalpha()         #全部为英文字母时返回True
False
>>> '1234abcd'.isdigit()         #全部为数字时返回True
False
>>> 'abcd'.isalpha()
True
>>> '1234.0'.isdigit()
False
>>> '1234'.isdigit()
True
>>> '九'.isnumeric()              #isnumeric()方法支持汉字数字
True
>>> '九'.isdigit()
False
>>> '九'.isdecimal()
False
>>> 'ⅣⅢⅩ'.isdecimal()
False
>>> 'ⅣⅢⅩ'.isdigit()
False
>>> 'ⅣⅢⅩ'.isnumeric()         #支持罗马数字
True

随机密码生成原理

>>> import string
>>> x = string.digits + string.ascii_letters + string.punctuation
>>> x
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> import random
>>> ''.join([random.choice(x) for i in range(8)])
'H\\{.#=)g'
>>> ''.join([random.choice(x) for i in range(8)])
'(CrZ[44M'
>>> ''.join([random.choice(x) for i in range(8)])
'o_?[M>iF'
>>> ''.join([random.choice(x) for i in range(8)])
'n<[I)5V@'

总结

本篇文章总结了有关字符串大量的用法函数,希望有助于大家对字符串有更全面的认识并能实战应用,下篇将列举三个例子,帮助大家更深刻的理解该知识点。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值