这是一项家庭作业。我只需轻推一下。
我正在尝试创建一个循环,当超过一定数量时,字符串的字母将被删除。
示例:
Enter Your String: David
Enter Your Amount: 4
Returns: Davi
到目前为止我做了什么:
word = raw_input("Enter your string:")
amount = raw_input("Enter your amount:")
word_length = len(word)
if word_length > amount:
for i in range(word_length):
if s[i] > amount:
这就是我所得到的。我不太确定使用哪种语法来删除位置大于word_length
的字母。
答案 0 :(得分:5)
Python中的字符串本身是不可变的 - 它不能被更改,并且不能删除字母。但是您可以根据字符串创建新的字符串对象。这样做的一种方法是slicing。
阅读官方Python教程的链接部分,直到找到所需内容。 :)
修改:如果您需要使用循环,如评论中所示,还可以使用其他技术:
创建一个空列表。
循环索引range(amount)
并将与当前索引对应的字母添加到列表中。
使用"".join(my_list)
再次将列表加入字符串。
iterim列表的目的是可以更改列表,而字符串 - 如前所述 - 是不可变的。
答案 1 :(得分:3)
你需要循环吗?否则,尝试字符串切片:
word = raw_input("Enter your string: ")
amount = int(raw_input("Enter your amount: "))
s = word[0:amount]
答案 2 :(得分:2)
不需要循环!
word = raw_input("Enter your string:")
amount = int(raw_input("Enter your amount:"))
word = word[:amount]
print word
第一步是读入您的值,并将金额转换为整数。
因为字符串是心中的字符列表,所以您可以从中获取子列表。
在Python中,[x:y]
表示法在区间[x,y]上从列表中获取子列表。
如果不提供x([:y]
),则间隔变为[0,y);如果你不提供y([x:]
):[x,len(theStr));如果你不提供([:]
),你会得到原始字符串!
奖励有趣的事实:
[x:y]
运算符是数组下标运算符[x]
的扩展。在大多数语言中,调用list[x]
将为您提供x处的元素。但是,在Python中,它的行为更像是遍历。例如,list[-1]
将为您提供列表中的最后一个元素。
[x:y:z]
运算符也存在,其中z是遍历期间使用的步长间隔。此运算符的有用情况包括以偶数索引(list[::2]
)获取元素,并反转列表(list[::-1]
)。
答案 3 :(得分:0)
你可以帮助切片
word = raw_input("Enter your string:")
amount = raw_input("Enter your amount:")
word=word[:int(amount)] #slicing the rest of unwanted characters
print word
答案 4 :(得分:0)
从Python中删除字符串中的字符很困难。解决给定问题的更好方法是使用切片,如其他人所建议的那样,或者如果必须使用循环,则通过在新字符串中收集所需的字符而不是从旧字符串中删除它们,即
s = raw_input()
n = int(raw_input())
new_s = ""
for i in range(n):
new_s = new_s + s[i]
答案 5 :(得分:0)
我猜你有两种方法