您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页Python 字符串2

Python 字符串2

来源:二三四教育网

在python中,把字符串这样的对象类型统称为 序列

索引和切片

几个例子:

# 从左到右,从0开始,从右到左,从-1开始
>>> num = "0123456789"
>>> num[0]
'0'
>>> num[0:8]
'01234567'
>>> num[:8]
'01234567'
>>> num[1:]
'123456789'
>>> num[:]
'0123456789'
>>> num[-1]
'9'
>>> num[-2]
'8'

字符串的基本操作

+ 连接字符串

>>> str1 = "hello"
>>> str2 = "sate"
>>> str1 + str2
'hellosate'
>>> str1 + " " + str2
'hello sate'
>>>

in

>>> str1 = "hello"
>>> "hel" in str1
True
>>> "helo" in str1
False

最值

是根据字符在计算机中编码来计算的

>>> str1 = "hello"
>>> max(str1)
'o'
>>> min(str1)
'e'

比较

两个字符串的比较是先将字符串中的符号转化为对应编码的数字,然后比较。
如果返回负数,则第一个小于第二个
如果返回整数,则第一个大于第二个
如果返回零,则两个相等。

>>> hehe = "hehe"
>>> haha = "haha"
>>> cmp(hehe,haha)
1
>>> cmp(haha,hehe)
-1
>>>

ord()是一个内建函数,可以返回某个字符的 ASCII 值,根据该值来比较。chr()正好反过来,根据整数值得到相应的字符。

>>> ord("a")
97
>>> chr(97)
'a'

*

字符串中的“乘法”

>>> a = "hahe"
>>> a*3
'hahehahehahe'
>>> "-"*20
'--------------------'

len()

>>> a = "hello"
>>> len(a)
5

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务