Python字符串

# -*- coding:UTF-8 -*-

def read_str():

    ###################
    # 字符串格式化
    ###################

    # 简单转换,整型、浮点型
    'price of eggs:%d' % 42  # output:price of eggs:42
    'PI:%f' % pi  # output:PI:3.141593

    # 字段宽度和精度
    '%10f' % pi  # output:'  3.141593'
    '%10.2f' % pi  # output:'      3.14'
    '%.2f' % pi  # output:'3.14'

    # 符号、对齐和用0填充
    # 用0填充宽度
    '%010.2f' % pi  # output:'0000003.14' 
    # '-'表示左对齐数值
    '%-10.2f' % pi  # output:'3.14' 


    ###################
    # 字符串方法
    ###################
    tag = "<a href=http://www.baidu.com>baidu indexpage</a>"
    print 'tag[8:28]=', tag[8:28]
    print 'tag[29:-4]=', tag[29:-4]

    # 字符串替换 replace
    tag.replace("www.baidu.com", "www.caoliu.com")
    print 'tag.replace=', tag.replace("www.baidu.com", "www.caoliu.com")

    # 字符串连接 join
    link = ['', 'user', 'bin', 'env']
    url = '/'.join(link)
    print 'url=', url

    # 字符串分割 split
    path = '/user/bin/env'
    split = path.split('/')
    print split

    # 字符串大小写转换
    s = 'i love you'
    print s.lower()  # 小写转换
    print s.upper()  # 大写转换

    # 字符串是否为大小写
    print s.islower()  # 是否为小写
    print s.isupper()  # 是否为大写

    # title 字符串标题
    print s.title()  # 所有单词的首字母大写

    # count 统计出现次数
    print s.count('o')

    # find 查找字符串位置,如果不存在,返回-1
    print s.find('you')

    # split 分割
    word = s.split()
    print word

    # join 合并
    string = '-'.join(word).upper()
    print string

    # replace 替换
    s.replace('you', 'lina')
    print s

    # strip 返回去除字符串两侧(不包括内部)空格的字符串
    names = ' hello word '
    print names.strip()  # output: 'hello world'

    # translate 字符串替换,replace用于替换整个字符串,translate用于只替换单个字符,可以同时进行多个替换


if __name__ == '__main__':
    read_str()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值