• python中常用的字符串和使用方法


    字符串

    字符串方法format,替代字符串用花括号括起来,
    "{}, {}, and {}".format("first", “second”, "third"),替换字段没有索引或者名称则按顺序替换,若有索引或名称,就按索引和名称替换。

    # 无索引按默认顺序替换
    txt = "{},{}, and {}"
    txt.format("first","second","third")
    >>> 'first,second, and third'
    
    # 索引替换
    txt = "{1},{2},{0}, and {1}"
    txt.format("first","second","third")
    >>> 'second,third,first, and second'
    
    # 按名称替换
    txt = "{name} is approximately {value: .2f}"
    txt.format(value = pi, name = "π")
    >>> 'π is approximately  3.14'

    字符串方法
    txt.center(width, "symbol"):居中,width:表示宽度;
    txt.ljust(width, "symbol"):居左;
    txt.rjust(width, "symbol"):居右;
    txt.zfill(width):居右,空位用0填充;
    txt.find("xxx", start, end):在字符串中找子串,返回第一个字符的索引,如果没有就返回-1;
    join:合并序列

    seq = ["1", "2", "3", "4"]
    sep = '+'
    sep.join(seq)
    >>> '1+2+3+4'
    1. txt.lower():返回小写字母;
    2. txt.title():词首字母大写;
    3. txt.replace('old', 'new'):替换;
    4. split:拆除
    '1+2+3+4'.split('+')
    >>> ["1", "2", "3", "4"]
    1. txt.strip():删除开头和结尾的空白;
    2. translate
    from string import maketrans   # 引用 maketrans 函数。
     
    intab = "aeiou"
    outtab = "12345"
    trantab = maketrans(intab, outtab)
     
    str = "this is string example....wow!!!";
    print str.translate(trantab);
    
    >>> 'th3s 3s str3ng 2x1mpl2....w4w!!!'
    
    [resource:](https://www.runoob.com/python/att-string-translate.html)
    判断是否符合条件,返回布尔值的方法。
    isdigit、islower、istitle等等…

    原文链接:https://blog.csdn.net/leeyns/article/details/106169733

  • 相关阅读:
    【leetcode】1562. Find Latest Group of Size M
    【leetcode】1561. Maximum Number of Coins You Can Get
    【leetcode】1560. Most Visited Sector in a Circular Track
    Python中用format函数格式化字符串的用法
    机器学习最常用优化之一——梯度下降优化算法综述
    python学习之argparse模块
    Ubuntu14.04安装NVIDIA显卡驱动
    Anaconda使用教程
    TensorFlow0.8代码目录结构讲解
    cmake编译opencv程序
  • 原文地址:https://www.cnblogs.com/LQZ888/p/13131402.html
Copyright © 2020-2023  润新知