簡體   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