字符串详解

字符串详解 字符串的创建与基本操作字符串在 Python 中是不可变的序列类型可以使用单引号、双引号或三引号来创建。不同的引号类型让我们能够灵活地处理各种文本内容。三引号特别适合创建多行字符串这在处理长文本或代码模板时非常有用。字符串支持转义字符让我们能够在文本中包含特殊字符。welcome_msghello worldsite_namepythondescription hello world hello world print(welcome_msg)print(site_name)print(description)hello_result\n hello world \n hello worldfile_pathC:\\Users\\aaa.pdfhello_textsss \ssss\print(hello_result)print(file_path)print(hello_text)字符串的索引与切片字符串作为序列类型支持索引和切片操作。这些操作让我们能够精确地提取和操作字符串的特定部分。切片操作还可以指定步长实现更灵活的字符串处理。problem_codeALG001_ARRAY_EASY#索引操作print(f第一个字符{problem_code[0]})print(f最后一个字符{problem_code[-1]})print(f最7一个字符{problem_code[6]})#切片操作problem_idproblem_code[0:6]problem_typeproblem_code[7:12]problem_levelproblem_code[13:]print(f题目ID:{problem_id})print(f题目类型:{problem_type})print(f难度等级:{problem_level})# 文件名处理filenamevideo_2024_01_15_final.mp4# 使用步长提取信息yearfilename[6:10]monthfilename[11:13]dayfilename[14:16]reversed_namefilename[::-1]extensionfilename[-4:]a1filename[4:]a2filename[::3]print(f年份{year})print(f月份{month})print(f日期{day})print(f反转文件名{reversed_name})print(f文件扩展名{extension})print(fa1{a1})print(fa2{a2})字符串的拼接与重复字符串拼接是日常编程中最常见的操作之一。Python 提供了多种拼接方式每种都有其适用场景。# 使用 join() 方法拼接info_parts[aaaa,是,platform,de,role]user_info..join(info_parts)print(user_info)# 字符串重复separtor*50print(separtor)print(aaaaa.center(50))print(separtor)skills[python,java,javascript,mysql,redis,docker]skill_text_efficient.join(skills)print(skill_text_efficient)字符串的常用方法user_input Hello World! # 大小写转换print(f转大写{user_input.upper()})print(f转小写{user_input.lower()})print(f首字母大写{user_input.capitalize()})print(f标题格式{user_input.title()})# 去除空白字符print(f去除两端空白{user_input.strip()})print(f去除左侧空白{user_input.lstrip()})print(f去除右侧空白{user_input.lstrip()})# 字符串查找和替换contentPython Java 教程print(f查找 python{content.find(Python)})print(f替换 python{content.replace(Python,Go)})print(f统计 教程 出现次数{content.count(教程)})#字符串判断方法username123aaaprint(fusername是否为字母数字{username.isalnum()})emailWEEEqq.comprint(f邮箱包含 {inemail})phone13811111111print(f手机号是否全为数字 {phone.isdigit()})# 密码强度检查passwordMyPassword123has_upperany(c.isupper()forcinpassword)has_lowerany(c.islower()forcinpassword)has_digitsany(c.isdigit()forcinpassword)print(f密码包含大写字母{has_upper})print(f密码包含小写字母{has_lower})print(f密码包含数字{has_digits})字符串的格式化字符串的格式化主要有 %、format、f-string这三种。# %格式化namesdsdfff.mp4process78.1size1024msg正在处理 %s进度%1f%%文件大小%d MB%(name,process,size)print(msg)# format()方法info姓名 {}进度{}大小{} MB.format(name,process,size)print(info)# 数字格式化score98.5formatted_salary分数{:.2f}.format(score)print(formatted_salary)# f-stringproblem_idASSFSprint(fproblem_id{problem_id})# 表达式计算a10b35cb/a dfe{b}/{a}({c:.1%})print(d)name张三mag姓名%s%nameprint(mag)正则表达式基础importredefclear_user_data():emails[qwwweqq.com,wewfsdvfvfvfb,qwsaadmin.cn]email_patternr^[a-zA-Z0-9._%-][a-zA-Z0-9.-]\.[a-zA-Z]{2,}$print(邮箱验证)foremailinemails:ifre.match(email_pattern,email):print(f{email}格式正确)else:print(f{email}格式错误)# 手机号提取text联系程序员张三手机 18798567732微信同号。备用联系方式18999868796phone_patternr1[3-9]\d{9}phonesre.findall(phone_pattern,text)print(f\n提取到的手机号{phones})# 密码强度检查passwords[123456,abc123,MyPassword123!,weakpwd]# 至少8位包含大小写字母、数字和特殊字符strong_passwordr^(?.*[a-z])(?.*[A-Z])(?.*\d)(?.*[$!%*?])[A-Za-z\d$!%*?]{8,}$print(\n密码强度检查)forpwdinpasswords:ifre.match(strong_password,pwd):print(f{pwd}强度足够)else:print(f{pwd}强度不足)clear_user_data()字符编码defhandle_encoding():chinese_text学习python助手utf8_byteschinese_text.encode(utf-8)gbk_byteschinese_text.encode(utf-8)print(f原文{chinese_text})print(fUTF-8编码{utf8_bytes})print(fGBK 编码{gbk_bytes})decoded_utf8utf8_bytes.decode(utf-8)decoded_gbkgbk_bytes.decode(gbk)print(fUTF-8 解码{decoded_utf8})print(fGBK 解码{decoded_gbk})try:decoded_utf8utf8_bytes.decode(utf-8)exceptUnicodeDecodeErrorase:print(f解码错误{e})safe_decodeutf8_bytes.decode(ascii,errorsignore)print(f忽略错误的解码结果:{safe_decode})handle_encoding()