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

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" x = "abcdefgh"
abcefgh 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.由于input内置的任何内容总是将是一个字符串。 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

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

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