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