乘方:**
取余:%
字符串:
定义:
单行字符串: “this"
多行字符串:""".....
....."""
\ 转义符
\n :会打印换行
\\n:会打印\n
+ 多个字符串链接
索引:
可以通过str[index]来找对应字符
-1可以取最后一位
-2可以取倒数第二位
切片:str[begin:end:step] 取值为begin≤x<end(前闭后开)
字符串格式化符号
符号 | 描述 |
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
%p | 用十六进制数格式化变量的地址 |
# 测试学员替换掉 %s 的位置
print("hood %s"%"测试school")
字符串之字面量插值
--“str”.format()
# 不设置指定位置,按默认顺序
>>> demo = "{} is bat man!".format("mansho")
>>> demo
'mansho is bat man!'
>>> demo = "{0} is {1} man!".format("mansho","spider")
>>> demo
'mansho is spider man!'
>>> demo = "{1} is {0} man!".format("mansho","spider")
>>> demo
'spider is mansho man!'
>>> demo = "{name} is {type} man!".format(name="mansho",type="spider")
>>> demo
'mansho is spider man!'
-- f”{变量}”
name = "Bob"
school = "hogwarts"
# 通过 f"{变量名}"
print(f"我的名字叫做{name}, 毕业于{school}")
字符串常用API之join
join
- 列表转换为字符串
a = ["h", "o", "o", "d", "y", "s", "h", "i"] # 将列表中的每一个元素拼接起来 print("".join(a))
>>> print("-".join(a))
h-o-o-d-y-s-h-i
字符串常用API之split
split
- 数据切分操作
# 根据split内的内容将字符串进行切分
demo = "my apple"
demo.split(" ") #使用空格来切分字符
字符串常用API之replace
replace
- 将目标的字符串替换为想要的字符串
>>> demo
'mansho is spider man!'
>>> demo.replace("mansho","David")
'David is spider man!'
字符串常用API之strip
strip
- 去掉首尾的空格
>>> str1 = " hello, there "
>>> str1.strip()
'hello, there'