字符串切片.py

"""
https://docs.python.org/zh-cn/3.10/tutorial/introduction.html

除了索引,字符串还支持 切片。
索引可以提取单个字符,
切片 则提取子字符串:

"""
word = 'Python'

# 1、对于使用非负索引的切片,如果两个索引都不越界,切片长度就是起止索引之差。
# 例如, word[1:3] 的长度是 2。
print(word[0:2])  # characters from position 0 (included) to 2 (excluded)
# Py
print(word[2:5])  # characters from position 2 (included) to 5 (excluded)
# tho

# 2、切片索引的默认值很有用;
# 省略开始索引时,默认值为 0,
# 省略结束索引时,默认为到字符串的结尾:
print('\n2、')
print(word[:2])  # character from the beginning to position 2 (excluded)
# 'Py'
print(word[4:])  # characters from position 4 (included) to the end
# 'on'
print(word[-2:])  # characters from the second-last (included) to the end
# 'on'

# 3、注意,输出结果包含切片开始,但不包含切片结束。
# 因此,s[:i] + s[i:] 总是等于 s。
print('\n3、')
print(word[:2] + word[2:])
# 'Python'
print(word[:4] + word[4:])
# 'Python'

# 4、索引越界会报错:
print('\n4、')
# print(word[42])  # the word only has 6 characters
# # IndexError: string index out of range

# 但是,切片会自动处理越界索引:
print(word[4:42])
# 'on'
print(word[42:])
# ''

# 5、Python 字符串不能修改,是 immutable 的。因此,为字符串中某个索引位置赋值会报错:
print('\n5、')
# word[0] = 'J'
# # TypeError: 'str' object does not support item assignment
# word[2:] = 'py'
# # TypeError: 'str' object does not support item assignment

# 要生成不同的字符串,应新建一个字符串:
print('J' + word[1:])
# 'Jython'
print(word[:2] + 'py')
# 'Pypy'

# 6、内置函数 len() 返回字符串的长度:
print('\n6、')
s = 'supercalifragilisticexpialidocious'
print(len(s))  # 34
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值