Python中批改字符串操作方法有很多,咱们挑重点的去学习,这里三个办法在工作中比拟罕用,别离是replace()、split()、join()。

【含意】:

所谓批改字符串,指就是通过函数的模式批改字符串中的数据。

【操作方法】:

一、replace() : 替换

1、语法

字符串序列.replace(旧子串,新子串,替换次数)

留神: 替换次数如果查出子串呈现次数,则替换次数为该子串呈现次数

2、疾速体验

# replace() --- 替换    需要:把and换成hemyStr = 'hello world and Python and java and php'new_str = myStr.replace('and', 'he')print(myStr)   # hello world and Python and java and phpprint(new_str)  # hello world he Python he java he php# 原字符串调用了replace函数后,原有字符串中的数据并没做任何批改,批改后的数据是replace函数电动的返回值# 阐明:replace函数有返回值,返回值是批改后的字符串# 字符串是不可变数据类型,数据是否能够扭转划分为:可变类型 和 不可变类型new_str = myStr.replace('and', 'he', 1)print(new_str)  # hello world he Python and java and phpnew_str = myStr.replace('and', 'he', 10)print(new_str)  # hello world he Python he java he php# 替换次数如果超出了子串呈现的次数,示意替换所有这个子串

留神: 数据依照是否能间接批改分为可变类型和不可变类型两种。字符串类型的数据批改的时候不能扭转原有的字符串,属于不能间接批改数据的类型即是不可变类型。

二、split() : 依照指定字符宰割字符串

1、语法

字符串序列.split(宰割字符,num)

留神: num示意的是宰割字符呈现的次数,行将来返回数据个数为num+1个

2、疾速体验

# split() --- 宰割 --- 返回一个列表,失落宰割字符myStr = 'hello world and Python and java and php'list1 = myStr.split('and')print(list1)  # ['hello world ', ' Python ', ' java ', ' php']list1 = myStr.split('and', 2)print(list1)  # ['hello world ', ' Python ', ' java and php']

留神: 如果宰割字符是原有字符串中的子串,宰割后则失落该子串。

三、join() : 用一个字符或子串合并字符串,即是将多个字符串合并为一个新的字符串

1、语法

字符或子串.join(多字符串组成的序列)

留神: num示意的是宰割字符呈现的次数,行将来返回数据个数为num+1个

2、疾速体验

# join() --- 合并列表外面的字符串数据为一个大字符串myList = ['aa', 'bb', 'cc']# 需要:最终后果为: aa...bb...ccnew_list = '...'.join(myList)print(new_list)  # aa...bb...ccnew_list = '/'.join(myList)print(new_list)  # aa/bb/cc

留神: 如果宰割字符是原有字符串中的子串,宰割后则失落该子串。

以上是python教程之字符串重点罕用批改办法的使用和了解,下一篇文章写字符串中非重点其余罕用操作方法中的批改办法。

文章借鉴起源:www.wakey.com.cn/