想要移除字串中第 n 個字元的 Python 程式?


在本文中,我們將在 Python 中從字串中移除第 n 個字元。假設我們有以下輸入字串 −

Amitdiwan

在移除第 n 個字元後(即第 2 個索引),輸出應該如下 −

Amt

從字串中移除第 n 個字元的 Python 程式

在這個示例中,我們將從字串中移除第 n 個字元 −

示例

def removechar(str1, n): x = str1[ : n] y = str1[n + 1: ] return x + y # Driver Code if __name__ == '__main__': str1 = input("Enter a String =") n = int(input("Enter the n-th index =")) print("The new string =\n") print(removechar(str1, n))

輸出

Enter a String= Jacob
Enter the n-th index = 2
The new string =
Jaob

無需使用者輸入,從字串中移除第 n 個字元的 Python 程式

在這個示例中,我們將無需使用者輸入,從字串中移除第 n 個字元 −

示例

def removechar(myStr, n): x = myStr[ : n] y = myStr[n + 1: ] return x + y # Driver Code if __name__ == '__main__': myStr = "Hello" print("String = ",myStr) # nth index # character to be removed at this index n = 2 print("The new string = ",removechar(myStr, n))

輸出

String = Hello
The new string = Helo

使用 for 迴圈,從字串中移除第 n 個字元的 Python 程式

在這個示例中,我們將使用 for 迴圈,從字串中移除第 n 個字元 −

示例

# Create a String myStr = "How are you?" # Display the initial string print("String = ",myStr) # nth index # The character is to be removed at this index n = 9 newStr = '' # for loop iteration for char in range(0, len(myStr)): if(char != n): # append newStr += myStr[char] # Display the updated string print("Updated string = ",newStr)

輸出

String = How are you?
Updated string = How are yu?

更新於: 2022-08-11

995 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.