03_字符串用法详解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | # 1, 字符串的格式化问题 # 我叫xxx,我住xxx,我今年xx岁,我喜欢做xxx # name = input("请输入你的名字:") # addr = input("请输入你的住址:") # s2 = f"我叫{name},我家住{addr}" # print(s2) # 2,索引和切片 # 索引:按照位置提取元素 # s = "我叫周杰伦,你呢,你叫周润发吗?" # print(s[0:5]) # print(s[:5]) # print(s[6:]) # print(s[:]) # print(s[-3:-1]) # print(s[-3:]) # s = "我爱你" # #可以给切片添加步长来控制切片的方向 # print(s[::-1]) #3, 字符串常用操作 #如何忽略大小写来进行判断 # verify_code = "xAd1" # user_input = input(f"请输入验证码({verify_code}):") # if verify_code.upper() == user_input.upper(): # print("验证码正确") # else: # print("验证码错误") # 4,替换和切割 # strip() # s = " 你好, 我叫 周杰 伦 " # s1 = s.strip() # print(s1) # 案例 # username = input("请输入用户名:").strip() # passwd = input("请输入密码:").strip() # if username == "admin": # if passwd == "123456": # print("登录成功") # else: # print("登录失败") # else: # print("登录失败") # replace(old,new)字符串替换 # s = "你好啊,我叫赛琳娜" # s1 = s.replace("赛琳娜", "周杰伦") # print(s1) # s = "he llo i am a good m an" # s1 = s.replace(" ", "") # print(s1) # split(用什么切割)字符串切割,用什么切就会损失掉谁 # a = "python_java_c#_c++_JavaScript" # # lst = a.split("_") # # print(lst) # lst = a.split("_JavaScript") # print(lst) #总结:replace(),split(),strip() ==>记住 # 5,查找和判断 # startwith(), isdigit(), in, not in, find # 6, 补充和总结 # s = "hello" # print(len(s)) # length 长度 # join() # a = "python_java_c#_c++_JavaScript" # lst = a.split("_") # print(lst) # lst = ['python', 'java', 'c#', 'c++', 'JavaScript'] # #用_把上面的人连起来 # s = "_".join(lst) # print(s) # 总结: ''' 1, f"{变量}" #格式化一个字符串 2, 索引和切片: 索引: 从0开始的, [0] 切片: s[start: end: step] #end位置的数据永远拿不到 3, 相关操作: 字符串操作对源字符串是不发生改变的 1. upper() # 在需要忽略大小写的时候使用 2. strip() # 可以去掉字符串左右两端的空白(空格,\t, \n) 3. replace() # 字符串替换 4. split() # 对字符串进行切割 5. join() # 拼接一个列表中的内容成为新字符串 6. startswith() # 判断字符串是否以xxx开头 7. len() # 字符串长度(内置函数) 字符串的循环和遍历 for c in s: print(c) #字符串的每一个字符 关于in: 1. 判断xxx是否在xxx中出现了 2. for循环 ''' # import os # path1 = "/usr/local" # path2 = "lib" # path3 = "python3" # result = os.path.join(path1, path2, path3) # print(result) # 输出: "/usr/local/lib/python3" import os path1 = os.path.dirname(__file__) path2 = "lib" path3 = "python3" result = os.path.normp ath(os.path.join(path1, path2, path3)) print (result) # 输出: "C:\usr\local\lib\python3"(在Windows系统上) |
本文作者:香菜哥哥
本文链接:https://www.cnblogs.com/yizhipanghu/p/17628153.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步