pyhton中s="hello",print(s[1:3])为啥输出结果为el?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pyhton中s="hello",print(s[1:3])为啥输出结果为el?相关的知识,希望对你有一定的参考价值。

参考技术A 因为下标默认从0开始 左到右0开始 右到左1开始.....1:3 就是1为e 3:l (0为h 1为e 2为l 3为l) 参考技术B

输出字符串的切片

切片为左闭右开形式,即所及结束是<第二个参数值的,即此处输出的是下标为1和2的字母

Pyhton 练习题

#############
练习
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:

>> L = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]
>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: ‘int‘ object has no attribute ‘lower‘
使用内建的isinstance函数可以判断一个变量是不是字符串:

>> x = ‘abc‘
>> y = 123
>> isinstance(x, str)
True
>> isinstance(y, str)
False
###########

答案:

L = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]
for s in L:
if isinstance(s, str):
L2.append(s)

####################

>> L2 = []
>> for s in L:
... if isinstance(s, str):
... L2.append(s)
...
>> L2
[‘Hello‘, ‘World‘, ‘Apple‘]

以上是关于pyhton中s="hello",print(s[1:3])为啥输出结果为el?的主要内容,如果未能解决你的问题,请参考以下文章

JAVA中String s = "hello"和String s = new String("hello")有啥区别啊?

String s="hello";String t="hellO";那么,s.equals(t)返回值是

String s="hello";s+="world";s变化了吗?原始的String对象的内容变了吗?

为啥“hello\\s*world”与“hello world”不匹配?

关于String s = new String("xyz"); 创建几个对象的问题

Python 编程 里面% "%s 和 % d" 代表的意思