Home > Back-end >  How to ask for a string, then ask for a position of string, then remove the letter and print the wor
How to ask for a string, then ask for a position of string, then remove the letter and print the wor

Time:10-27

Python

I want to create a program that asks the user for a string, then asks the user to select a position of the string to be removed, and then print the string without the letter of the position he chose to be removed. I'm struggling to find the correct way to do that.

x = input ('Enter a String: ')
sum = 0

if type(x) != str:
    print ('Empty Input')
else:
    y = input ('Enter the position of the string to be removed: ')

for i in range x(start, end):
    print ('New string is: ', x - i)

CodePudding user response:

Essentially how you can do this is simply using the .split() method to split it by the index of the string letter and join it with the join() method

x = input ('Enter a String: ')
sum = 0
if type(x) != str:
    print ('Empty Input')
else:
    y = int(input('Enter the position of the string to be removed: '))
x  = ''.join([''.join(x[:y]), ''.join(x[y 1:])])
print(x)

CodePudding user response:

The following part is unnecessary:

if type(x) != str:
    print ('Empty Input')

As whatever comes from input builtin is always going to be a string. The modified version of your code:

text = input('Enter a String: ')
if text == '': 
    print('Empty string')
else: 
    pos = int(input('Enter the position of the string to be removed: '))
    print(text[:pos]   text[pos 1:]) # TO remove value at  given index
    print(text[pos 1:]) # TO remove everything bofore the given index

SAMPLE RUN:

Enter a String: >? helloworld
Enter the position of the string to be removed: >? 4
hellworld
world

CodePudding user response:

Does this link help?

Excerpt from said page:

strObj = "This is a sample string"
index = 5
# Slice string to remove character at index 5
if len(strObj) > index:
    strObj = strObj[0 : index : ]   strObj[index   1 : :]

CodePudding user response:

The easiest way to achieve this is to use slice notation, and just leave out the character in the specified position:

x = input ('Enter a String: ')
if type(x) != str:
    print ('Empty Input')
else:
    y = int(input('Enter the position of the string to be removed: ')) or 1
    print(x[:y-1]   x[y:])

x = "abcdefgh"
abcefgh

  • Related