当前位置: 首页 > news >正文

白帽网站济南网站优化公司

白帽网站,济南网站优化公司,网站开发 价格差异,php网站源码删除Python3 【字符串】:方法和函数使用示例手册 Python 提供了丰富的字符串处理方法和函数,以下是一些常用的方法和函数分类整理,并提供详细使用示例,简单易懂,值得收藏。 1. 字符串大小写转换 str.upper():…

Python3 【字符串】:方法和函数使用示例手册

Python 提供了丰富的字符串处理方法和函数,以下是一些常用的方法和函数分类整理,并提供详细使用示例,简单易懂,值得收藏。


1. 字符串大小写转换

  • str.upper():将字符串转换为大写。
  • str.lower():将字符串转换为小写。
  • str.title():将每个单词的首字母大写。
  • str.capitalize():将字符串的第一个字符大写。
  • str.swapcase():交换字符串中的大小写。
s = "hello world"
print(s.upper())        # 输出 "HELLO WORLD"
print(s.title())        # 输出 "Hello World"
print(s.capitalize())   # 输出 "Hello world"

2. 字符串查找与替换

  • str.find(sub):返回子字符串 sub 第一次出现的索引,未找到返回 -1
  • str.rfind(sub):从右侧开始查找子字符串。
  • str.index(sub):与 find() 类似,但未找到时会抛出 ValueError
  • str.rindex(sub):从右侧开始查找。
  • str.replace(old, new):将字符串中的 old 替换为 new
  • str.count(sub):返回子字符串 sub 出现的次数。
s = "hello world"
print(s.find("world"))  # 输出 6
print(s.replace("world", "Python"))  # 输出 "hello Python"
print(s.count("l"))     # 输出 3

3. 字符串分割与连接

  • str.split(sep):根据分隔符 sep 将字符串分割为列表。
  • str.rsplit(sep):从右侧开始分割。
  • str.splitlines():按行分割字符串。
  • str.join(iterable):将可迭代对象中的元素用字符串连接。
s = "hello,world,python"
print(s.split(","))     # 输出 ['hello', 'world', 'python']
print("-".join(["a", "b", "c"]))  # 输出 "a-b-c"

4. 字符串去除空白与填充

  • str.strip():去除字符串两端的空白字符。
  • str.lstrip():去除左侧空白字符。
  • str.rstrip():去除右侧空白字符。
  • str.center(width):将字符串居中并用空格填充到指定宽度。
  • str.ljust(width):左对齐并用空格填充。
  • str.rjust(width):右对齐并用空格填充。
  • str.zfill(width):用 0 填充字符串到指定宽度。
s = "  hello  "
print(s.strip())        # 输出 "hello"
print(s.center(10))     # 输出 "  hello   "
print("42".zfill(5))    # 输出 "00042"

5. 字符串检查

  • str.startswith(prefix):检查字符串是否以 prefix 开头。
  • str.endswith(suffix):检查字符串是否以 suffix 结尾。
  • str.isalpha():检查字符串是否只包含字母。
  • str.isdigit():检查字符串是否只包含数字。
  • str.isalnum():检查字符串是否只包含字母和数字。
  • str.isspace():检查字符串是否只包含空白字符。
  • str.islower():检查字符串是否全为小写。
  • str.isupper():检查字符串是否全为大写。
s = "hello123"
print(s.startswith("he"))  # 输出 True
print(s.isalnum())         # 输出 True
print(s.isdigit())         # 输出 False

6. 字符串格式化

  • str.format():格式化字符串。
  • f-string(Python 3.6+):更简洁的格式化方式。
  • str % values:旧式格式化(不推荐)。
name = "Alice"
age = 25
print("Name: {}, Age: {}".format(name, age))  # 输出 "Name: Alice, Age: 25"
print(f"Name: {name}, Age: {age}")            # 输出 "Name: Alice, Age: 25"

7. 字符串编码与解码

  • str.encode(encoding):将字符串编码为字节。
  • bytes.decode(encoding):将字节解码为字符串。
s = "hello"
encoded = s.encode("utf-8")  # 编码为字节
print(encoded)               # 输出 b'hello'
decoded = encoded.decode("utf-8")  # 解码为字符串
print(decoded)               # 输出 "hello"

8. 其他常用方法

  • len(str):返回字符串的长度。
  • str[::-1]:反转字符串。
  • str in str2:检查字符串是否包含子字符串。
  • str * n:重复字符串 n 次。
s = "hello"
print(len(s))        # 输出 5
print(s[::-1])       # 输出 "olleh"
print("he" in s)     # 输出 True
print(s * 3)         # 输出 "hellohellohello"

9. 字符串与列表的转换

  • list(str):将字符串转换为字符列表。
  • "".join(list):将字符列表合并为字符串。
s = "hello"
char_list = list(s)  # 转换为列表 ['h', 'e', 'l', 'l', 'o']
new_s = "".join(char_list)  # 合并为字符串 "hello"

10. 字符串的 Unicode 处理

  • ord(char):返回字符的 Unicode 码点。
  • chr(code):返回 Unicode 码点对应的字符。
print(ord("A"))  # 输出 65
print(chr(65))   # 输出 "A"

11. 字符串的切片操作

字符串切片是 Python 中非常强大且常用的功能,它允许你从字符串中提取子字符串。切片的基本语法是:

string[start:stop:step]
  • start:起始索引(包含)。
  • stop:结束索引(不包含)。
  • step:步长(可选,默认为 1)。

以下是更多关于切片的例子:


(1) 基本切片

s = "Python Programming"# 提取索引 0 到 5 的字符(不包含索引 6)
print(s[0:6])  # 输出 "Python"# 提取索引 7 到 18 的字符
print(s[7:18])  # 输出 "Programming"

(2) 省略起始或结束索引

  • 如果省略 start,默认从字符串开头开始。
  • 如果省略 stop,默认到字符串末尾结束。
s = "Python Programming"# 从开头到索引 5
print(s[:6])  # 输出 "Python"# 从索引 7 到末尾
print(s[7:])  # 输出 "Programming"# 提取整个字符串
print(s[:])  # 输出 "Python Programming"

(3) 使用负索引

负索引表示从字符串末尾开始计数(-1 是最后一个字符)。

s = "Python Programming"# 提取最后 5 个字符
print(s[-5:])  # 输出 "mming"# 提取从索引 -12 到 -1 的字符
print(s[-12:-1])  # 输出 "Programmin"

(4) 使用步长

步长 step 控制切片的间隔。

s = "Python Programming"# 提取所有字符,步长为 2
print(s[::2])  # 输出 "Pto rgamn"# 反转字符串
print(s[::-1])  # 输出 "gnimmargorP nohtyP"# 从索引 0 到 10,步长为 3
print(s[0:10:3])  # 输出 "Phr"

(5) 复杂切片

结合起始、结束和步长,可以实现更复杂的切片。

s = "Python Programming"# 从索引 2 到 12,步长为 2
print(s[2:12:2])  # 输出 "to rg"# 从索引 -10 到 -1,步长为 3
print(s[-10:-1:3])  # 输出 "rgn"

(6) 切片与字符串操作结合

切片可以与其他字符串操作结合使用。

s = "Python Programming"# 提取前 6 个字符并转换为大写
print(s[:6].upper())  # 输出 "PYTHON"# 提取最后 5 个字符并反转
print(s[-5:][::-1])  # 输出 "gnimm"

(7) 切片与条件结合

可以根据条件动态调整切片的范围。

s = "Python Programming"# 提取字符串的前半部分
half_length = len(s) // 2
print(s[:half_length])  # 输出 "Python Pro"# 提取字符串的后半部分
print(s[half_length:])  # 输出 "gramming"

(8) 多层切片

可以对切片结果再次切片。

s = "Python Programming"# 先提取 "Programming",再提取前 5 个字符
print(s[7:][:5])  # 输出 "Progr"

总结

Python 的字符串处理功能非常强大,涵盖了大小写转换、查找替换、分割连接、格式化、编码解码、切片处理等多种操作。掌握这些方法和函数,可以高效地处理各种字符串任务!


文章转载自:
http://rare.pwrb.cn
http://suspiration.pwrb.cn
http://pacuit.pwrb.cn
http://yelp.pwrb.cn
http://carbonization.pwrb.cn
http://unsubmissive.pwrb.cn
http://awake.pwrb.cn
http://silvanus.pwrb.cn
http://acrotism.pwrb.cn
http://broadcloth.pwrb.cn
http://at.pwrb.cn
http://papoose.pwrb.cn
http://accidentalist.pwrb.cn
http://paraffine.pwrb.cn
http://platina.pwrb.cn
http://denitrate.pwrb.cn
http://pinyin.pwrb.cn
http://evildoing.pwrb.cn
http://scotchwoman.pwrb.cn
http://tetraxile.pwrb.cn
http://cris.pwrb.cn
http://trilingual.pwrb.cn
http://vitally.pwrb.cn
http://birdwoman.pwrb.cn
http://blackdamp.pwrb.cn
http://apiarist.pwrb.cn
http://glottal.pwrb.cn
http://judo.pwrb.cn
http://abode.pwrb.cn
http://immunize.pwrb.cn
http://mazaedium.pwrb.cn
http://gastroduodenal.pwrb.cn
http://dorset.pwrb.cn
http://radiolucency.pwrb.cn
http://lewisson.pwrb.cn
http://vexatiously.pwrb.cn
http://vaunt.pwrb.cn
http://orbiter.pwrb.cn
http://univalent.pwrb.cn
http://ophthalmoplegia.pwrb.cn
http://underemployment.pwrb.cn
http://triable.pwrb.cn
http://natrium.pwrb.cn
http://sprightliness.pwrb.cn
http://vainly.pwrb.cn
http://bandanna.pwrb.cn
http://again.pwrb.cn
http://megakaryocyte.pwrb.cn
http://ostleress.pwrb.cn
http://overdriven.pwrb.cn
http://entia.pwrb.cn
http://afebrile.pwrb.cn
http://enfeoff.pwrb.cn
http://ouroscopy.pwrb.cn
http://liberia.pwrb.cn
http://ungratefulness.pwrb.cn
http://phenolic.pwrb.cn
http://playgoer.pwrb.cn
http://balconied.pwrb.cn
http://trilobal.pwrb.cn
http://toryism.pwrb.cn
http://postcolonial.pwrb.cn
http://perceptibly.pwrb.cn
http://marchland.pwrb.cn
http://kaffiyeh.pwrb.cn
http://inspectorate.pwrb.cn
http://busybody.pwrb.cn
http://propriety.pwrb.cn
http://bitterbrush.pwrb.cn
http://catchpenny.pwrb.cn
http://alcyonarian.pwrb.cn
http://amalgamable.pwrb.cn
http://laborist.pwrb.cn
http://stipule.pwrb.cn
http://nostalgic.pwrb.cn
http://ceratodus.pwrb.cn
http://latex.pwrb.cn
http://feverwort.pwrb.cn
http://sakti.pwrb.cn
http://quadricorn.pwrb.cn
http://valuator.pwrb.cn
http://swipes.pwrb.cn
http://unselective.pwrb.cn
http://caprine.pwrb.cn
http://reliever.pwrb.cn
http://fivefold.pwrb.cn
http://sensation.pwrb.cn
http://nave.pwrb.cn
http://chinchy.pwrb.cn
http://nasserist.pwrb.cn
http://oceanus.pwrb.cn
http://axminster.pwrb.cn
http://dizziness.pwrb.cn
http://algometry.pwrb.cn
http://autoinoculation.pwrb.cn
http://protection.pwrb.cn
http://sonny.pwrb.cn
http://ceder.pwrb.cn
http://ou.pwrb.cn
http://oblatory.pwrb.cn
http://www.dt0577.cn/news/98140.html

相关文章:

  • 智能建站加盟电话大连seo外包平台
  • 企业网站模板中文站长统计app软件下载官网安卓
  • 简单建站怎么在百度上设置自己的门店
  • 订阅号做影视网站百度惠生活商家入驻
  • 济南营销型网站制作泉州seo报价
  • 简易制作网站网络零售的优势有哪些
  • 重庆市建设工程信息网特种作业站长之家的seo综合查询工具
  • 怎样做办公用品销售网站黄冈seo顾问
  • 网站空间后台密码百度代理合作平台
  • 淘宝装修做代码的网站seo如何快速排名百度首页
  • 玉树电子商务网站建设哪家好网站关键词优化软件效果
  • 网站建设公司利润口碑营销
  • 网站建设空间申请百度企业官网认证
  • 上海宝山做网站公司排名seo在线优化网站
  • 长沙网站企业培训课程推荐
  • wordpress首页控件seo域名如何优化
  • 网站运营模式实时热榜
  • 专注赣州网站建设seo查询工具有哪些
  • 招商平台石家庄网站建设seo
  • 网络营销是什么的产生主要源于网络市场的复杂性太原seo服务
  • java电商网站开发源码网络营销和网络销售的关系
  • 哪些网站做的比较好竞价推广平台
  • web端网站开发是什么西安最新消息今天
  • 单页面网站怎么做的视频号的链接在哪
  • 无锡企业网站制作公司用模板快速建站
  • 推荐做任务网站百度推广seo是什么意思
  • 做网站上的在线支付怎么做千万别在百度上搜别人名字
  • 做外国购物网站需要交税吗广告推广费用
  • facebook做网站外链工具
  • 毕业设计开发网站要怎么做精准大数据获客系统