Python字符串常用操作篇(下)

目录

一、字符串的查找与替换

1、查找

2、替换

 二、字符串分割和拼接

1、分隔

2、拼接

 三、字符串的指定字符的删除

1、方法介绍

2、代码例子

 四、转换字符串的指定字符

1、方法介绍

 2、代码例子

 五、字符串对齐

1、方法介绍

2、代码例子

 六、字符串的测试、过滤敏感词

1、字符串以指定开始或结束

 2、过滤敏感词

七、字符串的索引与切片

1、索引

 八、其他方法

1、index()、rindex()、count()方法

 2、组合使用方法

3、encode()、decode()

 九、例题解析

 十、文字排版工具

 十一、进制转换


一、字符串的查找与替换

1、查找

(1)find()方法:查找字符串中是否包含子串,若包含则返回子串首次出现的位置,否则返回-1

(2)代码例子

word = 't'
string = 'Python'
result = string.find(word)
print(result)

 

2、替换

(1)replace()方法:将当前字符串中的指定子串替换成新的子串,并返回替换后的新字符串,每次只能替换一个字符一个字符串,把指定的字符串参数作为一个整体对待,类似于Word、WPS、记事本、写字板等文本编辑器的“全部替换”功能,注意是返回一个新字符串,并不修改原来的字符串

(2)代码例子

string = 'He said, "you have to go forward, ' \
'Then turn left, Then go forward, and Then turn right."'
# 指定替换两次
new_string = string.replace("Then", "then",2)
print(new_string)

(3)replace()方法返回替换后的新字符串,可以直接再次调用replace()方法

text = "Python是一门非常棒的编程语言。"
print(text.replace('棒','优雅').replace('编程', '程序设计'))
print(text)


 二、字符串分割和拼接

1、分隔

(1)split()方法:可以按照指定分隔符对字符串进行分割,该方法会返回由分割后的子串组成的列表 

(2)代码例子

string= "Hello, my name is Wang Hong"
# 以空格作为分割符,并分割2次
print(string.split(' ', 2))
print(string.split(' ',maxsplit=2))  # # 最多分隔两次
string= "Hello, my name is Wang Hong"
print(string.split(' '))
print('1,2,3,4'.split(','))             # 使用逗号作为分隔符
text = 'Beautiful is better than ugly.'
print(text.split())                     # 使用空白字符进行分隔
print(text.split(maxsplit=1))           # 最多分隔一次
print(text.rsplit(maxsplit=2))          # 最多分隔两次
print('1,2,3,4'.split(','))             # 使用逗号作为分隔符

2、拼接

(1)join()方法:使用指定的字符连接字符串并生成一个新的字符串

(2)代码例子

symbol = '*'
world = 'Python'
print(symbol.join(world))
str = 'py' + 'thon'
str
print(','.join(['1', '2', '3', '4']))   # 使用逗号作为连接符
print(':'.join(map(str, range(1, 5))))  # 使用冒号作为连接符
print(''.join(map(str, range(1, 5))))   # 直接连接,不插入任何连接符


 三、字符串的指定字符的删除

1、方法介绍

字符串中可能会包含一些无用的字符(如空格),在处理字符串之前往往需要先删除这些无用的字符,删除字符串中的指定字符的方法有strip()、lstrip()和rstrip()

2、代码例子

str = " 123 546  "
str11 = str.strip(' ')
str11
str12 = str.lstrip(' ')
str12
str13 = str.rstrip(' ')
str13

text = '   ======test===#####   '
print(text.strip())          # 删除两侧的空白字符
print(text.strip('=# '))     # 删除两侧的=、#和空格


 四、转换字符串的指定字符

1、方法介绍

字母大小写转换:在特定情况下会对英文单词的大小写形式进行要求,表示特殊简称时全字母大写,如CBA;表示月份、周日、节假日时每个单词首字母大写,如Monday。Python中支持的方法有upper()、lower()、capitalize()和title()

 2、代码例子

'ABC'.lower()
'str1'.upper()
'I love python'.capitalize()
'I love python'.title()

text = 'Explicit is better than implicit.'
print(text.lower())
print(text.upper())
print(text.capitalize())
print(text.title())
print(text.swapcase())   # 把小写字母转换为大写字母并把大写字母转换为小写字母。  此部分了解,用的不多


 五、字符串对齐

1、方法介绍

字符串的对齐方式:在使用Word处理文档时可能需要对文档的格式进行调整,如标题居中显示、左对齐、右对齐等。Python提供了center()、ljust()、rjust()这3个方法来设置

2、代码例子

str1 = ' hhag  hh '
str1.center(100,'-')   #返回字符串宽度100,用‘-’填充
len(str1.center(100))    # 默认空格填充
str1.ljust(100)
str1.rjust(100)
print('居左'.ljust(20)+'结束')
print('居右'.rjust(20, '#'))        # 左侧使用井号填充
print('居中'.center(20, '='))       # 两侧使用等号填充


 六、字符串的测试、过滤敏感词

1、字符串以指定开始或结束

(1)startswith():测试字符串是否以指定的一个或者多个字符开始,若有多个字符串时,将字符串放入元组中

(2)endswith():测试字符串是否以指定的一个或者多个字符结束,若有多个字符串时,将字符串放入元组中

(3)代码例子

text = 'Simple is better than complex.'
print(text.startswith('simple'))   # 
print(text.startswith('Simple'))
print(text.endswith(('.', '!', '?')))   # ('.', '!', '?') 将多个字符串放入元组中

 2、过滤敏感词

(1)敏感词通常是指带有敏感政治倾向、暴力倾向、不健康色彩的词或不文明的词语,对于文章中出现的敏感词常用的处理方法是使用特殊符号(如“*”)对敏感词进行替换

import datetime
now = datetime.datetime.now()
sentence = '你是个坏蛋,傻瓜'
filter_sentence = sentence.replace("坏蛋",'**').replace("傻瓜",'***')
print(filter_sentence, " | ", now)


七、字符串的索引与切片

1、索引

(1)索引自0开始从左至右依次递增,这样的索引称为正向索引;若索引自-1开始,从右至左依次递减,则索引为反向索引

 

 (2)代码例子

str = 'Runoob'
str[-1]
str[0]

2、切片

(1)encode()方法:使用指定的编码格式将字符串转为字节串,默认utf-8

(2)decode()方法:使用指定的编码格式将字节串转为字符串,默认utf-8

(3)代码例子

bookName = '《Python可以这样学》'
print(bookName.encode())
print(bookName.encode('gbk'))
print(bookName.encode('gbk').decode('gbk'))
print(bookName.encode().decode('gbk'))   #不填,默认utf-8.用什么编码格式编码,就需要用什么编码格式解码


 八、其他方法

1、index()、rindex()、count()方法

(1)index():返回一个字符串在当前字符串中首次出现的位置,如不存在,抛出异常

(2)rindex():返回一个字符串在当前字符串中最后一次出现的位置,若不存在,抛出异常

(3)count():返回一个字符串在当前字符串中出现的次数,若不存在,返回0

text = '处处飞花飞处处;声声笑语笑声声。'
print(text.rindex('处'))
print(text.index('声'))
print(text.count('处'))

 2、组合使用方法

(1)maketrans():用来生成字符映射表

(2)translate():根据映射表中定义的对应关系转换字符串并替代其中字符串

(3)使用这两个方法的组合可以同时处理多个不同的字符

# 生成字符映射表,其中'0'对'零',一一对应。
table = ''.maketrans('0123456789', '零一二三四伍陆柒捌玖')
# 根据映射表,
print('Tel:30647359'.translate(table))

3、encode()、decode()

(1)encode():字符串使用指定的编码格式把字符串编码为字节串,默认使用UTF8编码格式

(2)decode():字节串使用指定的编码格式把字节串编码为字符串,默认使用UTF8编码格式

(3)注意:不同编码格式规则不一样,使用一种编码格式编码得到的字节串一般无法使用另一种编码格式正确解码

myName = '申小兮'
print(myName.encode())
print(myName.encode('gbk'))
print(myName.encode('gbk').decode('gbk'))


 九、例题解析

1、输入一个字符串,删除其中的重复空格,如果有连续的多个空格就只保留一个,然后输出处理后的字符串

text1 = "   iuie      ttthhj  "
text_temp = text1.split()
print(text_temp)
print(' '.join(text_temp))

2、输入一个字符串,把其中的元音字母i、o、a、e和u替换成对应的大写字母,然后输出新字符串

text = input('请输入一个字符串:')
table = ''.maketrans('aeoiu', 'AEOIU')
print(text.translate(table))

3、输入一个字符串,输出其中唯一字符组成的新字符串,要求新字符串中的字符顺序与其在原字符串中的相对顺序一样

text = input('请输入一个字符串:')
result = ''.join(sorted(set(text), key=lambda ch: text.index(ch)))
# 也可以写成下面的样子
# result = ''.join(sorted(set(text), key=text.index))
print(result)


 十、文字排版工具

1、文字排版工具一般具备删除空格、英文标点替换、英文单词大写功能

2、代码例子

# article = input("请输入您需要排版的内容:")

choice = int(input("请选择您想要使用的功能(1.删除空格  2.英文标点替换  3.英文单词大写):"))
if choice == 1:
    article = article.replace(" ", "")
elif choice == 2:
    choice2 = int(input("请选择您想使用的功能(1.英文标点全部替换为中文标点 2.中文标点全部替换为英文标点):"))
    if choice2 == 1:
        article = article.replace(",", ",")
        article = article.replace(".", "。")
        article = article.replace(":", ":")
        article = article.replace(";", ";")
        article = article.replace("!", "!")
        article = article.replace("?", "?")
    elif choice2 == 2:
        article = article.replace(",", ",")
        article = article.replace("。", ".")
        article = article.replace(":", ":")
        article = article.replace(";", ";")
        article = article.replace("!", "!")
        article = article.replace("?", "?")
    else:
        print("输入错误请重新输入!!!")
elif choice == 3:
    choice3 = int(input("请选择您想使用的功能(1.首字母大写,其余字母小写  2.全文英文首字母大写  3.全文单词大写):"))
    if choice3 == 1:
        article = article.capitalize()
    elif choice3 == 2:
        article = article.title()
    elif choice3 == 3:
        article = article.upper()
    else:
        print("输入错误请重新输入!!!")
else:
    print("输入错误请重新输入!!!")
print("排版后的内容:", article)

text = '''Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.'''

print(len(text))                 # 字符串长度,即所有字符的数量
print(text.count('is'))          # 字符串中单词is出现的次数
print('beautiful' in text)       # 测试字符串中是否包含单词beautiful
print('='*20)                    # 字符串重复
print('Good '+'Morning')         # 字符串连接

 


 十一、进制转换

1、十进制是实际应用中最常使用的计数方式,除此之外,还可以采用二进制、八进制或十六进制计数

2、2进制转换成10进制:int(n,2) 

n=input("请输入二进制:")
print(int(n,2))

3、10进制转换成16进制:hex(n)

n=int(input("请输入十进制:"))
print(hex(n))

3、16进制转换成10进制:int(n,16) 

n=input("请输入十六进制:")
print((int(n,16)))

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五秒法则

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值