频道栏目
首页 > 资讯 > Python > 正文

((Python基础教程))学习笔记 | 第03章 | 字符串

14-09-15        来源:[db:作者]  
收藏   我要投稿

第03章: 使用字符串

------

支持的操作

    索引切片增加元素删除元素更新元素查找元素(检查某个元素是否是序列中的一员)序列长度 最大值最小值其他内建函数
    >>> website='http://www.python.org'
    >>> website[-3:]='com'   #此操作不合法,因为字符串是不变,不能做修改
    
    Traceback (most recent call last):
      File "", line 1, in 
        website[-3:]='com'
    TypeError: 'str' object does not support item assignment
    ------

    字符串格式化:
    %s:转换说明符 元祖

    #字符型
    >>> str1 = "Hello, %s. %s enough for you ya?"
    >>> val1 = ('Jerry','Hot')
    >>> print str1 % val1
    Hello, Jerry. Hot enough for you ya?
    #浮点型
    >>> format = "PI with three decimals: %.3f"
    >>> from math import pi
    >>> print format % pi
    PI with three decimals: 3.142
    Note: 
    1. 使用列表的话,序列会理解成一个值,只有元祖和字典可以格式化一个以上的值
    2. 百分号: %%
    
    
    模板字符串
    #类似于linux中的变量替换,Template,substitute(将传的参数进行转换)
    >>> s = Template('$x,glorious $x!')
    >>> s.substitute(x='slurm')
    'slurm,glorious slurm!'
    #如果是单词的一部分的话,用{}括起来
    >>> s = Template('I love ${x}rry!')
    >>> s.substitute(x='She')
    'I love Sherry!'
    #如果是美元, 注意用$$来表示美元符,safe_substitute不会因缺少值或美元符而报错
    >>> s = Template('Using $$ buy ${x}!')
    >>> s.substitute(x='food')
    'Using $ buy food!'
    #利用字典提供键/值对
    >>> s = Template('A $thing must never $action')
    >>> d = {}
    >>> d['thing']='gentleman'
    >>> d['action']='show his socks'
    >>> s.substitute(d)
    'A gentleman must never show his socks'
    >>> s = Template('I am ${name},${age} years old.')
    >>> d = {'name':'Jerry','age':50}
    >>> s.substitute(d)
    'I am Jerry,50 years old.'
    #
    >>> s = '%s plus %s equals %s' % (1,1,2)
    >>> print s
    1 plus 1 equals 2
    ------

    基本的转换说明符号:

    (1)%字符,标志转换的开始
    (2)转换标志(可选)

    - 左对齐+ 转换值之前的正负号" " 空白字符,表示正数之前,保留空格0 转换值不够,则用0来填充 (3)最小字段宽度(可选):
    最小具有指定值的宽度如果是*,则值从元祖中读取 (4).精度值(可选)
    如果是实数,精度值表示后面的位数如果是字符,精度值表示后面的最大宽度如果是*,精度值从元祖中读取 (5)转换类型


    ------

    简单转换

    >>> print 'price of eggs is %d' % 12
    price of eggs is 12
    >>> print 'Hexadecimal price of eggs: %x' % 42
    Hexadecimal price of eggs: 2a
    >>> from math import pi
    >>> 'Pi: %f...' % pi
    Pi: 3.141593...
    >>> 'very inexact estimate of pi: %i' % pi
    very inexact estimate of pi: 3
    >>> 'Using str: %s' % 42L
    Using str: 42
    >>> 'Using repr: %r' % 42L
    Using repr: 42L
    ------

    字段的宽度和精度
    两个参数都是整数,用.分割,如果只给出精度,必须包含点号.

    >>> '%10f'   % pi   #宽度为10
    '  3.141593'    
    >>> '%10.2f' % pi   #宽度为10,精度为2
    '      3.14'
    >>> '%.2f'   % pi   #精度为2
    '3.14'
    >>> '%.5s'   % 'Hello, world!'   #字符串长度 
    'Hello'
    >>> '%.*s'   % (5,'Hello,World!')#字符串长度,其值从元祖中读取
    'Hello'
    ------

    ------

    ------

    ------

    ------

    ------

    ------

相关TAG标签
上一篇:HDOJ 5007 Post Robot
下一篇:HDU - 5012 Dice(BFS)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站