用于从字符串中删除第 n 个字符的 Python 程序?

programmingpythonserver side programming更新于 2025/3/14 13:32:17

在本文中,我们将从 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?

相关文章


有用资源