Python学习03
String操作
#字符串操作 s = 'alexwuSir' #首字母大写,其他小写 s = s.capitalize() print(s) #全部字母大写/小写 s = s.upper() s1 = s.lower() print(s, s1) #实际用途 验证码 code = "Ac3F" my_code = input("请输入验证码: ") if code.upper() == my_code.upper(): print("通过") else: print("错误") #大小写翻转 s = "aBc" s = s.swapcase() print(s) #每块首字母大写 - * 空格等特殊字符和隔开都会使得首字母大写,其他小写 s = "alex guo wang" s = s.title() print(s) #居中 s = "guo" s = s.center(20, "#") print(s) #tab补全 \t + 之前的字符补够8个字符位置,如果之前字符够8个字符,则额外加8个空格 s = "1222222\t2" s = s.expandtabs() print(s) #公共方法 l = len(s) print(l) #以什么开头 结尾endswith s = "guoyunhao" b = s.startswith("guo") b1 = s.startswith("o", 2, 4) print(b, b1) #查找find() 返回索引 找不到返回-1 index() 返回索引 找不到报错 i = s.find("uo") print(i, type(i))
s.index("uo")
#去两头空格等字符 s = " asd da d " s = s.strip()
#replace两个参数必须都为str s2 = s.replace(" ", "") print(s, s2) # %*都删除直到遇到不是的 s = "%*a*asd%" print(s.strip("%*")) # 数个数 s = "aa2asd" print(s.count("a")) # split 拆分 s = "alex aa guo" list = s.split(" ") print(list)
#字符串索引和切片 顾头不顾尾
s = "郭云皓是大帅哥"
s1 = s[0]
print(s1)
s6 = s[:]
print(s6)
s2 = s[1:4]
print(s2)
s3 = s[0:-1]
print(s3)
s4 = s[::-1]
print(s4)
s5 = s[0:4:2]
print(s5)
Str操作注意点:
# 'str' object does not support item assignment
# str内部的元素不能直接赋值
# str = 'guo'
# str[0] = 'G' ×
Int
i = 9
print(i.bit_length())
For循环
s = 'aasdvgsdg' for v in s: print(v) #循环同时获得循环到的index for i, v in enumerate(s): print(i, v)
for i in range(len(s)):
print(i, s[i])
bool
# 非空str -> bool 都为True print(bool(" "))
数据类型
#存储大量数据 #列表 list = [1, 2, 3, "郭大哥", [2, 4]] #元组 只读 tuple = (1, 2, 3, "郭大哥") a = list[2] print(a) a = tuple[3] print(a) #字典 dict = {"guo": [], "wang": []} #集合 无重复 set = {1, 2, 3, 3, "3"} print(set)
Example
输入计算式:1 + 2 或者 2 + 4 + 5 ...
user_input = input("请输入计算式: ") user_input.replace(" ", "") list = user_input.split("+") sum = 0 for i in list: sum += int(i) print(sum)
输入字符串,统计其中整数出现次数
#输入一个字符串,统计其中整数个数 s = "asd13ad4wr43563j1231aasdad8" i = 0 count = 0 while i < len(s): if s[i].isdigit(): while i < len(s) and s[i].isdigit(): i += 1 count += 1 else: i += 1 print(count)
# method 2 # s 是不可变的 在执行到for这一行时,原s将被缓存,循环里的s被改变不会影响到for循环的执行次数和i的值 # 如果这里遍历的是list,对list的修改会影响到for的遍历 # replace() 默认替换所有的 for i in s: if not i.isdigit(): s = s.replace(i, " ") # 这里split()如果不指名分隔符,所有连续空格将被去掉 l = s.split() print(len(l), l)