Python学习(三) 字符串

  • 数据结构
    • 字符串
    • 列表
    • 元组
    • 字典
    • 队列
    • 集合

  • 字符串

    • 创建字符串
      str1 = "Hello world!"
      str2 = "ABCDEFG"
      
    • 访问
      • 左闭右开
      str1 = "Hello world!"
      # 访问字符串中的单个字符或者子串
      print('str1:', str1)
      print('str1[0]:', str1[0])
      print('str1[0:5]:', str1[0:5])
      print('str1[6:11]:', str1[6:11])
      print('str1[-1]:', str1[-1])
      print('str1[9:10]:', str1[9:10])
      print('str1[-2:-1]:', str1[-2:-1])
      
    • 修改字符串
      • replace(old,new)
      • 不支持通过索引修改
      • 字符串拼接
      str1 = "Hi!"
      str2 = "Jack"
      # 通过拼接修改字符串
      str1 = str1 + str2
      print('After splicing str1:', str1)
      # 通过替换修改字符串:replace(old,new)
      str1 = str1.replace(str2, "Tom")
      print('After replacement str1:', str1)
      
    • 字符串运算符
      • 拼接
      • 剪切
      • 复制
      • 成员运算
      str1 = "Hello world!"
      str2 = "Jack"
      # 字符串拼接
      print('str1+str2:', str1 + str2)
      # 字符串截取
      print('str1[0:6]:', str1[0:6])
      # 字符串复制
      print('str2*2:', str2 * 3)
      # 成员运算:判断一个字符串是否包含某成员
      print('world in str1?', 'world' in str1)
      print('word in str1?', 'word' in str1) 
      
    • 字符串格式化
      #格式化为十进制:%d
      print('PI is approximately equal to %d (I)'%(3.1415926))
      #格式化字符串:%s
      print('PI is approximately equal to %s (II)'%(3.1415926))
      #格式化浮点数字,可指定小数点后的精度,默认为6位小数:%f
      print('PI is approximately equal to %f (III)'%(3.1415926))
      #格式化浮点数字,指定n位小数:%.nf
      print('PI is approximately equal to %.2f (IV)'%(3.1415926))
      #用科学计数法格式化浮点数:%e
      print('PI is approximately equal to %e (V)'%(3.1415926))
      #格式化为十进制:%d
      print('The road is about %d meters long (VI)'%(1234))
      #格式化无符号八进制数:%d
      print('The road is about %o meters long (VII)'%(1234))
      #格式化无符号十六进制数:%x
      print('The road is about %x meters long (VIII)'%(1234))
      
  • 上一篇:Python学习(二) 简数字和运算

  • 下一篇:Python学习(四) 列表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值