res = '123' print(type(res)) # <class 'str'> res = int(res) print(type(res)) # <class 'int'>
# 十进制转成其他进制 print(bin(100)) # 0b1100100 print(oct(100)) # 0o144 print(hex(100)) # 0x64 print(type(bin(100))) # <class 'str'> # 其他进制转成十进制 print(int('0b1100100', 2)) # 100 print(int('0o144', 8)) # 100 print(int('0x64', 16)) # 100
res = '123.12' print(type(res)) # <class 'str'> res = float(res) print(type(res)) # <class 'float'>
1.类型转换
任意数据类型都能转换成字符串类型: res = str(123) print(res, type(res)) # 123 <class 'str'> res = str('alearn') print(res, type(res)) # alearn <class 'str'> res = str([1, 2, 3]) print(res, type(res)) # [1, 2, 3] <class 'str'> res = str({"name":"alearn", 'age':18}) print(res, type(res)) # {'name': 'alearn', 'age': 18} <class 'str'> res = str((1, 2, 'aa')) print(res, type(res)) # (1, 2, 'aa') <class 'str'> res = str({1, 2, 'aa'}) print(res, type(res)) # {1, 2, 'aa'} <class 'str'>
2.索引取值
res = 'hello world!' print(res[0]) # h print(res[-1]) # ! 反向取值,索引值超过实际的就会报错
3.切片操作(步长)
res = 'hello world!' print(res[0:7]) # hello w print(res[0::2]) # hlowrd 第三位参数是决定步长的,取负值就是反向的意思 print(res[::-1]) # !dlrow olleh
4.长度计算
关键词:len() res = 'hello world!' print(len(res)) # 12 空格也算字符
5.移除首尾指定字符
关键词:strip # 默认消除前后空格 res = ' hello world! ' print(res.rstrip()) # hello world! right/left res_1 = '$$hello world!$$$$' print(res_1.strip("$")) # hello world!
6.按照指定字符切割字符串
res = 'alearn|123456|123' # 已知该词条中保存着用户昵称、账号、密码 res_list = res.split("|") print(res) # alearn|123456|123 print(res_list) # ['alearn', '123456', '123'] res_list = res.split("|", 1) print(res_list) # ['alearn', '123456|123'] 第二个参数控制切割的次数,默认从左往右,没有-1为从右向左一说
7.大小写转化
res = 'Alearn Go go go' print(res.upper()) # ALEARN GO GO GO 全大写 print(res.lower()) # alearn go go go 全小写 print(res.isupper()) # False 判断是否全大写 print(res.islower()) # False 判断是否全小写 print(res.title()) # Alearn Go Go Go 每个单词首字母大写 print(res.capitalize()) # Alearn go go go 句子开头大写 print(res.swapcase()) # aLEARN gO GO GO 大小写颠倒
9.判断是否以指定字符开头或结尾
s1 = "alearn 123 new old" print(s1.startswith('al')) # True print(s1.endswith("old")) # True
10.格式化输出
11.字符串拼接
12.替换字符串指定的字符
13.判断是否时纯数字
15.查找索引值
16.统计某字符出现的次数
17.填充
# 堆栈:先进后出 num = [] for i in range(1,5): num.append(i) print(num) for i in range(len(num)): num.pop() print(num) # 队列:先进先出 for i in range(1,5): num.append(i) print(num) for i in range(len(num)): num.pop(0) print(num)