str是Python中的一种常见数据类型,代表“字符串”(string)类型,即由若干个字符组成的文本序列。在Python中,字符串是不可变的(immutable),也就是说,一旦创建后就不能再被修改了,只能通过创建新的字符串来操作。接下来,我们将从多个方面对str的特点进行详细阐述。
一、str的创建
字符串在Python中可以通过单引号、双引号、三个单引号或三个双引号来创建。其中,单双引号创建的字符串没有区别,三个引号用来创建多行的字符串,其内部可以包含换行符。
str1 = 'hello world!' str2 = "hello world!" str3 = '''hello world!'''
除了使用直接赋值创建字符串之外,还可以使用str()函数将其他类型的值转为字符串类型,例如:
num1 = 123 num2 = 4.56 str_num1 = str(num1) # '123' str_num2 = str(num2) # '4.56'
在Python 3.x中,字符串默认使用Unicode编码,因此可以直接使用中文字符,例如:
chinese_str = '你好,世界!'
二、str的操作
1. 字符串连接
使用“+”运算符可以将两个字符串连接起来:
str1 = 'hello' str2 = 'world' str3 = str1 + str2 # 'helloworld'
2. 字符串重复
使用“*”运算符可以将一个字符串重复n次:
str1 = 'hello' str2 = str1 * 3 # 'hellohellohello'
3. 字符串截取
可以使用索引(从0开始)或切片来获取字符串的子串。例如:
str1 = 'hello world' char1 = str1[0] # 'h' char2 = str1[-1] # 'd' substr1 = str1[0:5] # 'hello' substr2 = str1[6:] # 'world' substr3 = str1[-5:-1] # 'worl'
4. 字符串长度
可以使用len()函数获取字符串的长度:
str1 = 'hello world' length = len(str1) # 11
5. 字符串查找
可以使用find()函数或index()函数在字符串中查找子串,并返回其第一次出现的位置(如果不存在则返回-1):
str1 = 'hello world' pos1 = str1.find('o') # 4 pos2 = str1.index('world') # 6 pos3 = str1.find('hi') # -1
6. 字符串替换
可以使用replace()函数替换字符串中的子串:
str1 = 'hello world' new_str1 = str1.replace('world', 'python') # 'hello python'
三、str的格式化
字符串格式化是将一个或多个值插入到字符串中的过程,通常会使用占位符(也称为格式化指示符)来指定应该被替换的值的类型和格式。在Python中,字符串格式化可以通过以下方式进行:
1. 使用占位符
使用“%”运算符来作为占位符,例如:
str1 = 'hello %s' % 'world' str2 = 'pi is equal to %.2f' % 3.14159
占位符的类型和格式规范如下:
类型 | 描述 | 示例 |
---|---|---|
%d | 有符号十进制整数 | 123 |
%u | 无符号十进制整数 | 123 |
%f | 浮点数 | 3.14 |
%e | 科学计数法表示的浮点数 | 1.23e+4 |
%g | 浮点数或科学计数法表示的浮点数(自动选择) | 3.14或1.23e+4 |
%c | 单个字符 | ‘a’ |
%s | 字符串 | ‘hello’ |
%x | 十六进制整数 | 0x12ab |
%% | 表示“%”字符 | ‘%’ |
2. 使用f字符串
在Python 3.6及以上版本中,可以使用f字符串(也称为格式化字符串)来简化字符串格式化的过程,例如:
name = 'Alice' age = 18 fstr = f'My name is {name}, I am {age} years old.'
f字符串在大括号中可以直接使用变量名,也可以进行简单运算和调用函数。
四、str的方法
除了前面提到的字符串操作之外,str还定义了许多常用的方法,例如:
1. upper()和lower()
返回字符串的大写或小写形式:
str1 = 'hello world' new_str1 = str1.upper() # 'HELLO WORLD' new_str2 = str1.lower() # 'hello world'
2. strip()和lstrip()和rstrip()
返回去除字符串两端空格后的结果,strip()表示去除两端空格,lstrip()表示去除左侧空格,rstrip()表示去除右侧空格。
str1 = ' hello world ' new_str1 = str1.strip() # 'hello world' new_str2 = str1.lstrip() # 'hello world ' new_str3 = str1.rstrip() # ' hello world'
3. split()
返回将字符串按照指定的分隔符(默认为空格)拆分后的结果:
str1 = 'hello,world' lst1 = str1.split(',') # ['hello', 'world']
4. join()
返回使用指定字符串将一个列表中的元素拼接起来的结果:
lst1 = ['hello', 'world'] str1 = ','.join(lst1) # 'hello,world'
5. count()
返回字符串中指定子串出现的次数:
str1 = 'hello world' count1 = str1.count('l') # 3 count2 = str1.count('world') # 1
还有许多其他有用的方法,例如replace()、find()、index()等,可以查看Python官方文档(https://docs.python.org/3/library/stdtypes.html#string-methods)进行了解。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/197222.html