python入门之字符串

1、字符串表现形式

单引号或是双引号形式

>>> 'hello'
'hello'
>>> "hello"
"hello"

2、多行字符串

三重引号,"""…""" 或 ‘’’…’’’

""" 
hello
python
"""

3、字符串合并

使用+号合并字符串

>>> 'py' + 'thon'
'python'

4、字符串重复

使用*生成重复字符串

>>> 3*'hello'
'hellohellohello'

5、字符串自动合并

相邻的两个或多个字符串(引号标注的字符)会自动合并

>>> 'Py' 'thon'
'Python'

拆分长字符串时,这个功能特别实用:

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

注:
这项功能只能用于两个字面值,不能用于变量或表达式
合并多个变量,或合并变量与字面值,要用 +

6、字符串索引

字符串支持索引(下标访问),第一个字符的索引是 0。

>>> 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、字符串切片

字符串支持切片,即提取子字符串

>>> 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]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

8、字符串修改

为字符串中某个索引位置赋值会报错,要生成不同的字符串,应新建一个字符串

>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

9、字符串长度

内置函数 len() 返回字符串的长度

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

测开

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值