python 字符串详解

1. 字符串的概念

在计算机编程中,字符串是文本数据类型的基本元素。在Python中,字符串是被单引号、双引号或三引号包围的文本。

'hello world'

"python is cool"

'''three single quotes'''

"""three double quotes"""

1.1 字符串的索引

字符串的每个字符都有一个唯一的索引,从0开始。我们可以使用方括号[]和索引来访问字符串中的字符。例如:

str = 'hello'

print(str[0]) #输出 'h'

print(str[1]) #输出 'e'

字符串还支持负索引,-1表示最后一个字符,-2表示倒数第二个字符,以此类推。例如:

str = 'hello'

print(str[-1]) #输出 'o'

print(str[-2]) #输出 'l'

1.2 字符串的切片

除了索引外,我们还可以使用切片操作来访问字符串的一部分。切片操作使用方括号[]和冒号:,格式为[start:end:step],其中start表示起始位置,默认为0;end表示结束位置(不包含),默认为字符串长度;step表示步长,默认为1。例如:

str = 'hello world'

print(str[2:7]) #输出 'llo w'

print(str[:5]) #输出 'hello'

print(str[6:]) #输出 'world'

print(str[::2]) #输出 'hlowrd',每隔一个字符取一个

1.3 字符串的常用方法

Python中的字符串有许多内置方法。

1.3.1 查找子字符串

Python中常用的字符串查找方法是find()和index(),两者的功能类似,区别在于如果查找的子字符串不存在,find()会返回-1,而index()会抛出异常。

str = 'hello world'

print(str.find('o')) #输出 4

print(str.index('o')) #输出 4

print(str.find('x')) #输出 -1

print(str.index('x')) #引发异常

1.3.2 替换子字符串

Python中替换字符串的方法是replace(),它会返回一个新字符串,原始字符串不受影响。

str = 'hello world'

new_str = str.replace('world', 'python')

print(new_str) #输出 'hello python'

print(str) #输出 'hello world'

1.3.3 大小写转换

Python中有三种字符串大小写转换方式:lower(),upper(),title()。

str = 'hello world'

print(str.upper()) #输出 'HELLO WORLD'

print(str.lower()) #输出 'hello world'

print(str.title()) #输出 'Hello World'

1.3.4 去除空格

Python中常用的去除字符串前后空格的方法是strip(),它会返回一个新字符串,原始字符串不受影响。

str = '   hello world    '

new_str = str.strip()

print(new_str) #输出 'hello world'

print(str) #输出 ' hello world '

1.3.5 判断字符串是否以指定子字符串开头或结尾

Python字符串中常用的判断方法是startswith()和endswith(),它们会查看字符串是否以指定的子字符串开头或结尾。

str = 'hello world'

print(str.startswith('hello')) #输出 True

print(str.endswith('d')) #输出 True

2. 字符串的格式化

字符串的格式化是在一个字符串中插入值的过程,Python提供了多种格式化方法。

2.1 字符串格式化操作符

Python中最基本的字符串格式化方法是使用占位符%s,需要插入值的位置用%s替换,然后使用%操作符将值插入字符串中。例如:

name = 'Tom'

age = 20

print('My name is %s, and I am %d years old.' % (name, age)) #输出 'My name is Tom, and I am 20 years old.'

其中%d表示整数,%s表示字符串。

2.2 format()方法

Python中另一种常用的字符串格式化方法是使用format()方法,可以直接在字符串中插入花括号{}作为占位符,然后使用format()方法将值插入字符串中。例如:

name = 'Tom'

age = 20

print('My name is {}, and I am {} years old.'.format(name, age)) #输出 'My name is Tom, and I am 20 years old.'

format()方法还支持位置参数和命名参数。位置参数的格式为{0},{1},{2}...,命名参数使用花括号中的变量名。例如:

name = 'Tom'

age = 20

print('My name is {0}, and I am {1} years old. Hello {0}!'.format(name, age)) #输出 'My name is Tom, and I am 20 years old. Hello Tom!'

print('My name is {name}, and I am {age} years old.'.format(name='Tom', age=20)) #输出 'My name is Tom, and I am 20 years old.'

format()方法还可以用于格式化数字,例如指定小数点后的位数:

pi = 3.1415926

print('{:.2f}'.format(pi)) #输出 '3.14'

2.3 f-string

Python 3.6引入了一种新的字符串格式化方法,即f-string。它使用类似于字符串插值的语法,在字符串前面加上字母f,花括号中使用变量名即可。例如:

name = 'Tom'

age = 20

print(f'My name is {name}, and I am {age} years old.') #输出 'My name is Tom, and I am 20 years old.'

f-string的优点是简洁、易读,而且可以在花括号中使用任意Python表达式。

3. 字符串的操作

3.1 字符串的拼接

Python中有两种字符串拼接的方法,一种是使用加号+,另一种是使用join()方法。

str1 = 'hello'

str2 = 'world'

str3 = str1 + ' ' + str2

print(str3) #输出 'hello world'

str4 = '-'.join([str1, str2])

print(str4) #输出 'hello-world'

使用join()方法时,需要将多个字符串放入一个列表中作为参数,join()会将这些字符串按指定的分隔符拼接起来。

3.2 字符串的重复

Python中可以使用乘法操作符*来重复一个字符串。

str = 'hello'

print(str * 3) #输出 'hellohellohello'

3.3 字符串的分割

Python中使用split()方法对字符串进行分割,并返回分割后的子字符串列表。

str = 'hello world'

lst = str.split()

print(lst) #输出 ['hello', 'world']

split()方法默认以空白字符(空格、制表符、换行符等)进行分割,也可以指定分隔符。

str = '1,2,3'

lst = str.split(',')

print(lst) #输出 ['1', '2', '3']

3.4 字符串的替换

Python中使用replace()方法替换字符串中的子字符串。

str = 'hello world'

new_str = str.replace('world', 'python')

print(new_str) #输出 'hello python'

4. 总结

字符串是Python编程中的重要组成部分,有着丰富的内置方法和格式化方式,同时也有着许多常用的操作。

重要强调:

字符串的不可变性,指的是字符串对象内部的元素无法被修改,如果想修改字符串中的内容,需要创建一个新的字符串。例如:

str = 'hello'

str[0] = 'H' #引发异常

如果需要修改字符串中的一个字符,可以使用切片操作。例如:

str = 'hello'

new_str = 'H' + str[1:]

print(new_str) #输出 'Hello'

需要注意的是,Python字符串的每个操作实际上都会创建一个新的字符串对象,因此在处理大量字符串时需要注意内存的消耗。

免责声明:本文来自互联网,本站所有信息(包括但不限于文字、视频、音频、数据及图表),不保证该信息的准确性、真实性、完整性、有效性、及时性、原创性等,版权归属于原作者,如无意侵犯媒体或个人知识产权,请来电或致函告之,本站将在第一时间处理。撸码网站发布此文目的在于促进信息交流,此文观点与本站立场无关,不承担任何责任。

后端开发标签