如何询问字符串,然后询问字符串的位置,然后删除字母并打印没有字母的单词



Python

我想创建一个程序,要求用户输入一个字符串,然后要求用户选择要删除的字符串的位置,然后打印没有他选择删除的位置的字母的字符串。我正在努力寻找正确的方法。

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)

实现这一点的最简单方法是使用切片表示法,只需省略指定位置的字符:

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

本质上,您可以简单地使用.split()方法通过字符串字母的索引将其拆分,并使用join()方法将其连接

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)

以下部分是不必要的:

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

因为来自input内建的内容总是一个字符串。您代码的修改版本:

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

样本运行:

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

这个链接有帮助吗?

摘录自上述页面:

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 : :]

相关内容

最新更新