python3 字符串操作
字符串是 Python 中最常用的数据类型。我们可以使用引号( ’ 或 " )来创建字符串。
1. 创建字符串
创建字符串很简单,只要为变量分配一个值即可。例如:
stringStr1 = 'hello word'
stringStr2 = 'python 是世界上最好的语言'
print(stringStr1)
print(stringStr2)
执行结果
hello word
python 是世界上最好的语言
2. 访问字符串中的值
语法:stringName[startIndex: endIndex]
startIndex:头下标;endIndex:尾下标。左闭右开
实例
stringStr1 = 'hello word'
stringStr2 = 'python 是世界上最好的语言'
print(stringStr1[1: 2])
print(stringStr2[0: 8])
实例执行结果
e
python 是
如果下标大于数组的长度,会报异常(数组越界)
print(stringStr1[100])
Traceback (most recent call last):
File "F:/python/HelloWord/hello/string.py", line 10, in <module>
print(stringStr1[100])
IndexError: string index out of range
字符串的更新
截取原字符串,在其截取的字符串之后拼接自定义的字符串;
实例
stringStr1 = 'hello word'
stringStr1 = stringStr1[: 6] + "java"
print(stringStr1)
实例执行结果
hello java
字符串格式化
基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
实例:
print("计算: %d + %d = %d" % (10, 20, 30))
实例执行结果:
计算: 10 + 20 = 30
常用的格式化符号
符号 | 描述 |
---|---|
%d | 格式化整数 |
%s | 格式化字符串 |
%f | 格式化浮点型 |
%x | 格式化无符号十六进制数 |
%u | 格式化无符号整型 |
%e | 用科学计数法格式化浮点数 |
f-string语法
f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去
实例:
name = '小黄的白'
x = 11
print(f'{name}')
result = f'{x * 2}'
print("表达式的计算结果 %s" %result)
执行实例结果:
小黄的白
表达式的计算结果 22
python的内置函数
函数描述 | 实例 | 结果 |
---|---|---|
capitalize()将字符串的第一个字符转换为大写 | print(“hello”.capitalize()) | Hello |
count(str, beg= 0,end=len(string))返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 | print(‘hello llwwasg’.count(‘l’, 0, 5)) | 2 |
endswith(suffix, beg=0, end=len(string))检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False. | print(“hello”.endswith(‘o’)) | True |
expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。 | print(“hello python”.expandtabs()) | hello python |
find(str, beg=0, end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1 | print(‘hello’.find(‘l’)) | 2 |
index(str, beg=0, end=len(string))跟find()方法一样,只不过如果str不在字符串中会报一个异常。 | print(‘hello’.find(‘l’)) | 2 |
len(string),返回字符串的长度 | print(len(‘hello’)) | 5 |
lower(),将字符串中的大写全部转小写 | print(‘HELlO’.lower()) | hello |
upper(),将字符串中的小写全部转大写 | print(“hello”.upper()) | HELLO |
replace(old, new [, max])把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次 | print(‘hello’.replace(‘l’, ‘n’, 1)) | henlo |
split(str="", num=string.count(str))以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串 | print(‘hello kkhlg’.split(‘l’, 2)) | [‘he’, ‘’, ‘o kkhlg’] |