# 示例代码:Python 字符串截取
# 定义一个字符串
s = "Hello, World!"
# 使用切片操作进行字符串截取
# 语法: s[start:stop:step]
# start: 开始索引(包含)
# stop: 结束索引(不包含)
# step: 步长,默认为1
# 截取从索引2到索引5的子字符串(包括索引2,不包括索引5)
substring_1 = s[2:5]
print(f"截取从索引2到索引5的子字符串: {substring_1}") # 输出: llo
# 截取从索引7到最后的子字符串
substring_2 = s[7:]
print(f"截取从索引7到最后的子字符串: {substring_2}") # 输出: World!
# 截取从开头到索引5的子字符串
substring_3 = s[:5]
print(f"截取从开头到索引5的子字符串: {substring_3}") # 输出: Hello
# 每隔两个字符截取一次
substring_4 = s[::2]
print(f"每隔两个字符截取一次: {substring_4}") # 输出: Hlo ol!
# 反转字符串
reversed_string = s[::-1]
print(f"反转字符串: {reversed_string}") # 输出: !dlroW ,olleH
上一篇:网络爬虫python代码
下一篇:python ord()函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站