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("The remaining characters are : ")
print(my_string)输出
Characters from odd index have been removed The remaining characters are : H hr il
说明
定义了一个名为“remove_odd_index_characters”的方法,它以字符串作为参数。
创建一个空字符串。
遍历字符串,将每个元素的索引除以 2.
如果余数不为 0,则将其视为奇数索引,并将其删除。
在主方法中,调用该方法,并定义字符串。
此字符串作为参数传递给该方法。
输出显示在控制台上。
广告
DS(数据结构)
Networking
RDBMS
OS(操作系统)
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP