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)
uj5u.com熱心網友回復:
基本上如何做到這一點是簡單地使用 .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)
uj5u.com熱心網友回復:
實作這一點的最簡單方法是使用切片表示法,并且只留下指定位置的字符:
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
uj5u.com熱心網友回復:
以下部分是不必要的:
if type(x) != str:
print ('Empty Input')
因為無論來自inputbuiltin 總是將是一個字串。您的代碼的修改版本:
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
uj5u.com熱心網友回復:
請問此鏈接幫助?
摘自上述頁面:
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 : :]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/336987.html
