字符串可以用单引号,双引号,三引号成对括起来,索引用[]界定,切片用[:]来省略和连接,这点类似于Matlab。
>>> s1='Python'
>>> s2=' is cool!'
>>> str=s1+s2
>>> str
'Python is cool!'
>>> str[0]
'P'
>>> str[2:5]
'tho'
>>> str[:2]
'Py'
>>> str[3:]
'hon is cool!'
>>> str*2
'Python is cool!Python is cool!'
>>> '-'*8
'--------'
>>> str[-1]
'!' 字符串下标从0开始,最后一个字符的索引是-1。加号来连接,*用来重复。>>> str2='Python\n is cool!'
>>> str2
'Python\n is cool!'
>>> print str2
Python
is cool!
Python字符串操作详解
本文介绍了Python中字符串的基本操作,包括使用单引号、双引号和三引号定义字符串的方法,字符串的索引和切片操作,以及字符串的连接与重复。通过实例展示了如何进行字符串的拼接和重复,并解释了负数索引的概念。
1643

被折叠的 条评论
为什么被折叠?



