
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
2.3.2 字符串
字符串是Python中常见的数据类型,用单引号、双引号和三引号都可以创建,例如:

单引号、双引号在单独使用时没有区别,它们也可以配合使用,例如:

三引号支持换行,例如:

字符串属于不可变的数据类型,对它修改后产生的新字符串需要赋值给新的变量,原字符串仍保持不变。以下是几个常用的字符串内置方法。
1. 查找方法find()
语法格式为str.find(sub[,start[,end]])。
find()用于查找字符串中是否包含子字符串sub。如果指定start和end范围,则在指定范围内检查。如果含有子字符串,则返回第一次出现时的位置,以索引值表示,否则返回-1。例如:

2. 替换方法replace()
语法格式为str.replace(old_str,new_str[,max_num])。
replace()用于将指定的字符串替换为目标字符串。old_str为被替换的字符串,new_str为新字符串。max_num是可选的,用于指定替换次数,不指定则默认为全部替换。例如:

3. 拆分方法split()
语法格式为str.split(str="",num=string.count(str))。
split()用于指定分隔符对字符串进行拆分,返回拆分后的列表。参数str为分隔符,默认为空格。num表示拆分次数,默认为-1,即拆分所有。例如:

4. 合并方法join()
语法格式为str.join(sequence)。
join()是split()的逆方法,可以将序列中的元素用指定的字符串作为分隔符合并成一个字符串。str为合并时的分隔符,sequence为要合并的序列。例如:

