【python】字符串元素的访问与截取
字符串元素的访问与截取
文章目录
- 字符串元素的访问与截取
- 示例1:
- 示例2:
- 示例3:
- 示例4:
- 示例5:
字符串元素的访问与截取
模板:string[start:stop:step]
start:要截取一系列元素的起始元素下标,默认为0
stop:要截取一系列元素的最后一个下标+1,默认为字符串长度
step:访问字符串元素的步长,默认为1
示例1:
输入: card_number = ‘4111-1111-4555-1142’
输出: card_number_reversed = ‘4111’
card_number = '4111-1111-4555-1142'
# 截取card_number字符串的前4个元素
card_number_reversed = card_number[0:4:1]
示例2:
输入: card_number = ‘4111-1111-4555-1142’
输出: card_number_reversed = ‘41’
card_number = '4111-1111-4555-1142'
# 在card_number字符串前4个元素中,每隔一个元素截取一个元素
card_number_reversed = card_number[0:4:2]
示例3:
输入: card_number = ‘4111-1111-4555-1142’
输出: card_number_reversed = ‘2411’
card_number = '4111-1111-4555-1142'
# 逆序截取card_number字符串后4个元素
# 字符串的最后一个元素下标为-1,往前走1步,步长为-1
card_number_reversed = card_number[-1:-5:-1]
示例4:
输入: card_number = ‘4111-1111-4555-1142’
输出: card_number_reversed = ‘2411555411111114’
card_number = '4111-1111-4555-1142'
# 将card_number字符串逆序
card_number_reversed = card_number[::-1]
示例5:
输入: card_number_reversed = ‘2411555411111114’
输出: odd_digits = 21551111
card_number_reversed = '2411555411111114'
# 截取card_number_reversed字符串奇数位置上的字符
odd_digits = card_number_reversed[::2]