• Python字符串_序列_len函数


    一,字符串是序列

    字符串和整形、浮点数以及布尔值很不一样。一个字符串是一个序列,意味着是对其他值的有序排列。

    字符串就是一串有序的字符。你可以通过方括号操作符,每次去访问字符串中的一个字符:

    >>> fruit = 'banana'

    >>> letter = fruit[1]

    第二个语句选择了 fruit 这个字符串的序号为1的字符,并把这个字符赋值给了 letter 这个变量。方括号内的内容叫做索引,索引指示了你所指定的字符串中字符的位置。

    但得到的结果和我们预期的有点不一样:

    >>> fruit = 'banana'

    >>> letter = fruit[1]

    >>> letter

    'a'

    我们习惯性地认为banana 的第[1]个字符应该是 b,而不是 a。但对于计算机科学家来说,索引是字符串从头开始的偏移量,所以真正的首字母偏移量应该是0,所以这里letter得到的值是a

    >>> fruit = 'banana'

    >>> letter = fruit[0]

    >>> letter

    'b'

    索引为0,指向的字符为b.

    所以 b 就是字符串 banana 的第【0】个字符,而 a 是第【1】个,n 就是第【2】个了。

    另外,我们可以在方括号内的索引中使用变量和表达式:

    >>> fruit = 'banana'

    >>> i = 1

    >>> fruit[i]

    'a'

    >>> fruit[i+1]

    'n'

    >>> fruit[i+2]

    'a'

    但要注意的事,索引的值必须是整形的。否则你就会遇到类型错误了:

    >>> letter = fruit[2.5]

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    TypeError: string indices must be integers

    二,len长度

    len是一个内置函数,会返回一个字符串中字符的长度:

    >>> fruit = 'banana'

    >>> len(fruit)

    6

    要得到一个字符串的最后一个字符,你可能会想到去利用 len 函数:

    >>> fruit = 'banana'

    >>> length = len(fruit)      调用函数len,并赋值给length

    >>> last = fruit[length]

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    IndexError: string index out of range

    这里报错字符索引超出范围,原因就是banana这个字符串在第【6】个位置是没有字母的。因为我们从0开始数,所以这一共6个字母的顺序是0到5号。因此要得到最后一次字符,你需要在字符串长度6的基础上减去1,得到5才对。

    >>> last = fruit[length-1]

    >>> last

    'a'

    或者你也可以用负数索引,意思就是从字符串的末尾向前数几位。fruit[-1]这个表达式给你最后一个字符,fruit[-2]给出倒数第二个,依此类推。

    >>> last = fruit[-1]

    >>> last

    'a'

    >>> last = fruit[-2]

    >>> last

    'n'

    结束。

  • 相关阅读:
    LeetCode 1110. Delete Nodes And Return Forest
    LeetCode 473. Matchsticks to Square
    LeetCode 886. Possible Bipartition
    LeetCode 737. Sentence Similarity II
    LeetCode 734. Sentence Similarity
    LeetCode 491. Increasing Subsequences
    LeetCode 1020. Number of Enclaves
    LeetCode 531. Lonely Pixel I
    LeetCode 1091. Shortest Path in Binary Matrix
    LeetCode 590. N-ary Tree Postorder Traversal
  • 原文地址:https://www.cnblogs.com/liusingbon/p/13159401.html
Copyright © 2020-2023  润新知