A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-program-for-removing-i-th-character-from-a-string/ below:

Python program for removing i-th character from a string

Python program for removing i-th character from a string

Last Updated : 10 Nov, 2024

In this article, we will explore different methods for removing the i-th character from a string in Python. The simplest method involves using string slicing.

Using String Slicing

String slicing allows us to create a substring by specifying the start and end index. Here, we use two slices to exclude the i-th character.

Python
s = "PythonProgramming"

# Index of the character to remove
i = 6

# Removing i-th character
res = s[:i] + s[i+1:]
print(res)

Explanation:

Let's explore other different methods to removing i-th character from a string:

Using a for Loop

A basic for loop can also be used to iterate over each character in the string and build a new string that excludes the i-th character.

Python
s = "PythonProgramming"

# Index of character to remove
i = 6

# Initialize an empty string to store result
res = ''

# Loop through each character in original string
for j in range(len(s)):
  
    # Check if current index is not index to remove
    if j != i:
      
        # Add current character to result string
        res += s[j]

print(res)
Using join() with List Comprehension

Another way to remove the i-th character from a string is by using join() and a list comprehension. The idea of approach is similar to the above loop method.

Python
s = "PythonProgramming"

# Index of the character to remove
i = 6

# Removing i-th character using list comprehension
res = ''.join([s[j] for j in range(len(s)) if j != i])
print(res)

Explanation:


Program for removing i-th character from a string


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4