繁体   English   中英

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

[英]How to ask for a string, then ask for a position of string, then remove the letter and print the word without the letter

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)

基本上如何做到这一点是简单地使用 .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)

这个链接有帮助吗?

摘自上述页面:

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

实现这一点的最简单方法是使用切片表示法,并且只留下指定位置的字符:

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

以下部分是不必要的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM