python学习笔记---字符串操作
Python中的字符串操作是程序中最常见,也是必不可少的一个部分。字符串操作主要包括字符串的定义、常用方法、格式化输出等。本篇文章将重点讲解Python中的字符串操作。
一、字符串的定义
在Python中,字符串可以由单引号、双引号或三引号括起来,如:
a = 'hello world' b = "hello world" c = '''hello world''' d = """hello world"""
其中,a和b是一样的,都是用单引号或双引号定义的字符串;c和d都是用三引号定义,可以实现多行字符串。
二、字符串的常用方法
1. find
find方法用于查找字符串中是否包含某个子字符串,如果包含,则返回 次出现的位置,否则返回-1。
str = 'hello world'
print(str.find('world')) # 6
print(str.find('hello')) # 0
print(str.find('python')) # -1
2. index
index方法与find方法类似,但如果找不到子字符串,会抛出异常。
str = 'hello world'
print(str.index('world')) # 6
print(str.index('hello')) # 0
#print(str.index('python')) # ValueError: substring not found
3. replace
replace方法用于将字符串中的某个子字符串替换为另一个字符串。
str = 'hello world'
print(str.replace('world', 'python')) # hello python
4. split
split方法将字符串按照指定的分隔符分割成一个列表,分隔符默认为空格。
str = 'hello world'
print(str.split()) # ['hello', 'world']
print(str.split('o')) # ['hell', ' w', 'rld']
5. join
join方法是split方法的逆向操作,用于将一个字符串列表按照指定的分隔符连接成一个字符串。
lst = ['hello', 'world']
print(' '.join(lst)) # hello world
print('-'.join(lst)) # hello-world
6. strip
strip方法用于去除字符串两端的空格和制表符,可选参数为要去除的字符。
str = ' hello world '
print(str.strip()) # hello world
print(str.strip(' l')) # ello world
三、格式化输出
Python提供了多种格式化输出的方法,常用的有%、format和f-string。
1. % 格式化输出
使用%作为格式化占位符。
name = 'Tom'
age = 18
score = 95.5
print('name:%s age:%d score:%.1f' % (name, age, score))
输出结果为:name:Tom age:18 score:95.5
2. format格式化输出
使用{}作为格式化占位符。
name = 'Tom'
age = 18
score = 95.5
print('name:{} age:{} score:{:.1f}'.format(name, age, score))
输出结果为:name:Tom age:18 score:95.5
3. f-string格式化输出
f-string是Python3.6+新增的格式化字符串方法,使用f作为前缀。
name = 'Tom'
age = 18
score = 95.5
print(f'name:{name} age:{age} score:{score:.1f}')
输出结果为:name:Tom age:18 score:95.5
总结:
本篇文章主要介绍了Python中的字符串操作,包括字符串的定义、常用方法和格式化输出等。熟练掌握字符串操作是Python编程的基础之一,对于进行字符串处理的程序开发具有重要的意义。
