• string


    多行文本以\结尾,换行还是要用\n

    hello = "This is a rather long string containing\n\
    several lines of text just as you would do in C.\n\
        Note that whitespace at the beginning of the line is\
     significant."
    
    print(hello)

    多行原格式文本用"""或者'''围绕。里面的换行就是换行

    print("""\
    Usage: thingy [OPTIONS]
         -h                        Display this usage message
         -H hostname               Hostname to connect to
    """)

    string可以用+号和*号

    >>> word = 'Help' + 'A'
    >>> word
    'HelpA'
    >>> '<' + word*5 + '>'
    '<HelpAHelpAHelpAHelpAHelpA>'

    string可以被索引[]

    >>> word[4]
    'A'
    >>> word[0:2]
    'He'
    >>> word[2:4]
    'lp'
    >>> word[:2]    # The first two characters
    'He'
    >>> word[2:]    # Everything except the first two characters
    'lpA'

    python中的string是不可改变的,只能从新创建字符串,和c不同

    >>> word[0] = 'x'
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: 'str' object does not support item assignment
    >>> word[:1] = 'Splat'
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: 'str' object does not support slice assignment
    
    #只能从新创建字符串
    >>> 'x' + word[1:]
    'xelpA'
    >>> 'Splat' + word[4]
    'SplatA'
    
    >>> word[:2] + word[2:]
    'HelpA'
    >>> word[:3] + word[3:]
    'HelpA'

    索引没有越界问题

    >>> word[1:100]
    'elpA'
    >>> word[10:]
    ''
    >>> word[2:1]
    ''

    索引可以是负值,从右往左数字符

    >>> word[-1]     # The last character
    'A'
    >>> word[-2]     # The last-but-one character
    'p'
    >>> word[-2:]    # The last two characters
    'pA'
    >>> word[:-2]    # Everything except the last two characters
    'Hel'
     +---+---+---+---+---+
     | H | e | l | p | A |
     +---+---+---+---+---+
     0   1   2   3   4   5
    -5  -4  -3  -2  -1

    len()内置函数用来得到字符长度

    >>> s = 'supercalifragilisticexpialidocious'
    >>> len(s)
    34

     合并迭代子

    >>> def concat(*args, sep="/"):
    ...    return sep.join(args)
    ...
    >>> concat("earth", "mars", "venus")
    'earth/mars/venus'
    >>> concat("earth", "mars", "venus", sep=".")
    'earth.mars.venus'

     赋值技巧

    >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
    >>> non_null = string1 or string2 or string3
    >>> non_null
    'Trondheim'
  • 相关阅读:
    阅读配色
    电影资源下载
    处理原电影音频
    导入字幕实操
    视频剪辑实操
    录音实操
    py2neo的一些基础用法
    debug时报错:UnicodeDecodeError: 'utf8' codec can't decode byte 0xe6 in position 1023: unexpected end of data
    MYSQL MDL监控
    MYSQL 表磁盘大小(INNODB_SYS_TABLESPACES)
  • 原文地址:https://www.cnblogs.com/wangjixianyun/p/2836592.html
Copyright © 2020-2023  润新知