Python程序去除字符串中奇数索引值的字符
当需要从字符串的奇数索引中删除字符时,定义了一种将字符串作为参数的方法。
以下是相同的演示-
示例
def remove_odd_index_characters(my_str):
new_string = ""
i = 0
while i < len(my_str):
if (i % 2 == 1):
i+= 1
continue
new_string += my_str[i]
i+= 1
return new_string
if __name__ == '__main__':
my_string = "Hi there Will"
my_string = remove_odd_index_characters(my_string)
print("Characters from odd index have been removed")
print("剩下的字符是: ")
print(my_string)输出结果Characters from odd index have been removed 剩下的字符是: H hr il
解释
定义了一个名为“remove_odd_index_characters”的方法,该方法将字符串作为参数。
创建一个空字符串。
遍历字符串,将每个元素的索引除以2。
如果余数不为0,则将其视为奇数索引,并将其删除。
在main方法中,调用方法,定义字符串。
该字符串作为参数传递给该方法。
输出显示在控制台上。
热门推荐
10 英语寄信祝福语范文简短
11 结婚祝福语创意简短刻字
12 怀猪宝宝祝福语简短
13 新婚男士祝福语大全简短
14 校长转岗祝福语大全简短
15 离职祝福语简短高级精辟
16 业主售楼祝福语简短精辟
17 艺术生联考祝福语简短
18 老师祝您订婚祝福语简短