博客
关于我
字符串类型及format格式化
阅读量:321 次
发布时间:2019-03-04

本文共 2880 字,大约阅读时间需要 9 分钟。

Python 字符串操作指南

字符串是编程中常用的数据类型之一,在Python中,字符串操作功能非常强大,可以满足各种开发需求。本文将详细介绍Python字符串的相关知识,包括字符串的基本操作、格式化方法、字符串操作符以及常用字符串处理函数。

1. 字符串的基本概念

字符串是由一系列字符组成的数据结构,在Python中,字符串可以用单引号 ' 或双引号 " 包裹。单行字符串和多行字符串的区别在于使用不同的边界符:

  • 单行字符串:print('这是一个单行字符串')
  • 多行字符串:print("这是一个多行字符串。\n新的一行")

示例代码

print('这是一个单行字符串')print("这是一个多行字符串。\n新的一行")

输出结果:

这是一个单行字符串这是一个多行字符串。新的一行

2. 字符串的索引与切片

字符串索引可以用来检索特定位置的字符,而切片操作可以提取字符串中的一段内容。

  • 索引:s = '好好学习 天天向上'print(s[0])print(s[-1])

    • print(s[0]) 输出第一个字符:h
    • print(s[-1]) 输出最后一个字符:g
  • 切片:s = '好好学习 天天向上'print(s[2:])

    • 输出:学习 天天向上

示例代码

s = '好好学习 天天向上'print(s[0])  # 输出第一个字符print(s[-1])  # 输出最后一个字符print(s[2:])  # 输出从第二个字符开始的所有字符

输出结果:

hg学习 天天向上

3. format方法

format方法是一种强大的字符串格式化工具,可以用来美观地排版字符串内容。

  • 简单格式化:print('好好{} 天天{}'.format('学习','向上'))

    • 输出:好好学习 天天向上
  • 指定参数位置:print("好好{1},天天{0}".format('向上','学习'))

    • 输出:好好学习,天天向上

示例代码

print('好好{} 天天{}'.format('学习','向上'))  # 输出:好好学习 天天向上print("好好{1},天天{0}".format('向上','学习'))  # 输出:好好学习,天天向上

4. 格式控制

format方法还支持格式控制符,可以用来调整输出格式:

  • 填充:print('{:<25}'.format('python'))

    • 输出:python
  • 对齐:print('{:>25}'.format('python'))

    • 输出:python
  • 宽度:print('{:^25}'.format('python'))

    • 输出:python
  • 精度:print('{:.2f}'.format(3.1415926))

    • 输出:3.14
  • 类型:print('{:x}'.format(1010))

    • 输出:1010(十六进制)

示例代码

print('{:<25}'.format('python'))  # 输出:python                                     print('{:>25}'.format('python'))  # 输出:python         print('{:^25}'.format('python'))  # 输出:python          print('{:*^25}'.format('python'))  # 输出:*********python**********print('{:.2f}'.format(3.1415926))  # 输出:3.14print('{:x}'.format(1010))  # 输出:1010

5. 字符串操作符

以下是一些常用的字符串操作符:

  • +:连接字符串
  • *:重复字符串
  • in:判断子串是否存在

示例代码

x = 'hello world'y = 'I love python'print(x + y)  # 输出:hello worldI love pythonprint(x * 2)  # 输出:hello worldhello worldprint('hello' in x)  # 输出:True

输出结果:

hello worldI love pythonhello worldhello worldTrue

6. 字符串处理函数

以下是一些常用的字符串处理函数:

  • len(s):返回字符串长度
  • str(s):将任意类型转换为字符串
  • chr(s):返回字符对应的Unicode编码
  • ord(s):返回字符的Unicode编码
  • hex(s):返回整数的十六进制表示
  • oct(s):返回整数的八进制表示

示例代码

s = 'python'print(len(s))  # 输出:6print(str(s))  # 输出:pythonprint(ord('h'))  # 输出:104print(chr(104))  # 输出:hprint(hex(255))  # 输出:0xffprint(oct(8))  # 输出:0o10

输出结果:

6python104h0xff0o10

7. 字符串处理方法

以下是一些常用的字符串处理方法:

  • str.upper():将字符串转换为大写
  • str.lower():将字符串转换为小写
  • str.split(seq=None):将字符串按序列分割
  • str.count(sub):统计子串出现次数
  • str.replace(old, new):将旧子串替换为新子串
  • str.center(width, fillchar):居中字符串并填充
  • str.strip(chars):去掉左右两侧指定字符
  • str.join(iter):将字符串添加到迭代器中

示例代码

s = 'I love python'print(s.split())  # 输出:['I', 'love', 'python']print(s.split('o'))  # 输出:['I l', 've pyth', 'n']print(s.count('o'))  # 输出:2print(s.replace('o', '#'))  # 输出:I l#ve pyth#nprint('python'.center(10, '*'))  # 输出:**python**print('   python    '.strip())  # 输出:pythonprint(','.join('python'))  # 输出:p,y,t,h,o,n

输出结果:

['I', 'love', 'python']['I l', 've pyth', 'n']2I l#ve pyth#npythonpythonp,y,t,h,o,n

8. 小结

上述内容涵盖了Python字符串的基本操作、格式化方法以及常用字符串处理函数和方法。通过这些操作,我们可以轻松地处理字符串数据,满足日常开发需求。

转载地址:http://voqq.baihongyu.com/

你可能感兴趣的文章
Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
查看>>
Python 从数据库中存储和检索密码的最安全方法
查看>>
Python语言及其应用 - 知识点遍历
查看>>
Python 优化提速的 8 个小技巧
查看>>
Python 余弦相似度与皮尔逊相关系数 计算
查看>>
python 使用execjs 报编码错误解决办法,UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 145: il
查看>>
python 使用filetype校验文件
查看>>
Python 使用flush函数将缓冲区数据立即写磁盘
查看>>
python 使用in判断不准确,in不好使
查看>>
Python 使用pandas 进行查询和统计详解
查看>>
Redis 配置文件redis.conf详细解释
查看>>
python网络爬虫(2)——scrapy框架的基础使用
查看>>
python网络爬虫实例教程试读_Python网络爬虫实战教程(全套完整版) - 学途无忧网 - 做技术的王者 - Powered By EduSoho...
查看>>
Python 使用哈希函数用于加密
查看>>
Python 依赖管理的革新——Poetry 深度解析
查看>>
python 保留精度及增加去除数字的千位分隔符(金额化数字)
查看>>
python 倒计时 9,8,7,。。。。。。0
查看>>
Python 入门开发学习笔记之数据的增删改查
查看>>
Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境
查看>>
Python 八大排序算法合集
查看>>