对 Python 字符串 学习简要总结

  1. Python对字符串的操作包括  '…' ,"…" ,' ' '…' ' '," " "…" " ",“+”,“*”,用于转义的“ \ ”,索引text[1],切片text[1:2],字符串长度len()等;
  2. '…'和"…"基本上是相同的,只能处理单行字符串;
    >>> 'hallo word'
    'hallo word'
    >>> "hallo 'python'"
    "hallo 'python'"
    >>>
  3. '''…'''和"""…"""基本上同样是相同的,不同于单重引号的是可以处理多行字符串,在第一行末尾添加 \ 可以防止行结尾包含在字符串内;
    print("""\
    Usage: thingy [OPTIONS]
         -h                        Display this usage message
         -H hostname               Hostname to connect to
    """)
    print("""\
    Usage: thingy [OPTIONS]
         -h                        Display this usage message
         -H hostname               Hostname to connect to
    """)  ##这个不太懂  求大神帮忙解答纠正
  4. “ \ 用于转义,用来表示一些特殊的符号,如果使用原始字符串的话,需要在字符串前面添加“r”;
    >>> print('C:\some\name')  # here \n means newline!
    C:\some
    ame
    >>> print(r'C:\some\name')  # note the r before the quote
    C:\some\name
  5. “+”可以让两个或以上字符串相连,相邻的两个或多个字符串会自动相连在一起,“*”可以让字符串重复出现,只适用于字面值,不适用于变量和表达式
    >>> # 3 times 'un', followed by 'ium'
    >>> 3 * 'un' + 'ium'
    'unununium'
    >>>
    >>> 'Py' 'thon'
    'Python'
  6. python支持字符串索引,使用word[1]来索引,索引只可以获得单个字符,第一个字符串的索引为0,并且索引可以为负数,从右到左,python的索引是不可变的;
    >>> word = 'Python'
    >>> word[0]  # character in position 0
    'P'
    >>> word[5]  # character in position 5
    'n'
    >>>
    >>> word[-1]  # last character
    'n'
    >>> word[-2]  # second-last character
    'o'
    >>> word[-6]
    'P'
  7. 同样的python也支持切片,使用word[1:3]来切片,切片会让你获得一个字符串,索引总包括开头,又排除结尾,所以word[:2]+word[2:]始终等于word,Python的切片是不可变得;
    >>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
    'Py'
    >>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
    'tho'
    >>> word[:2] + word[2:]
    'Python'
    >>> word[:4] + word[4:]
    'Python'
    
  8. Python中常用len()计算字符串长度;
    >>> s = 'supercalifragilisticexpialidocious'
    >>> len(s)
    34

参考  Python中文文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值