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)
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)
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 : :]
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: '))
print(x[:y-1] + x[y:])
x = "abcdefgh"
abcefgh
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.