简体   繁体   English

Python从字符串中删除字母

[英]Python Removing Letters From a String

This is a homework assignment. 这是一项家庭作业。 I just need a nudge. 我只需要轻推一下。

I'm trying to create a loop in which the letters of a string will be removed when it is beyond a certain number. 我正在尝试创建一个循环,当字符串超出一定数字时,该字符串中的字母将被删除。

Example: 例:

Enter Your String: David
Enter Your Amount: 4
Returns: Davi

What I've made so far: 到目前为止,我所做的是:

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:

And that's just about as far as I've gotten. 就我所知而已。 I'm not very sure as to which syntax I use to delete the letters that are in positions greater than word_length . 我不确定使用哪种语法删除位置大于word_length的字母。

A string itself in Python is immutable -- it cannot be changed and letters cannot be deleted. Python中的字符串本身是不可变的-不能更改,不能删除字母。 But you can create new string objects based on your string. 但是您可以根据您的字符串创建新的字符串对象。 One way of doing so is slicing . 这样做的一种方法是切片

Read through the linked section of the official Python tutorial until you find what you need. 通读Python官方教程的链接部分,直到找到所需的内容。 :) :)

Edit : If you need to use a loop, as suggested in your comment, another technique is also possible: 编辑 :如果您需要使用循环,如注释中所建议,则另一种技术也是可能的:

  1. Create an empty list. 创建一个空列表。

  2. Loop over the indices range(amount) and add the letter corresponding to the current index to your list. 循环遍历索引range(amount)然后将与当前索引相对应的字母添加到列表中。

  3. Join the list to a string again using "".join(my_list) . 使用"".join(my_list)将列表再次连接到字符串。

The purpose of the iterim list is that a list can be altered, while a string -- as said before -- is immutable. iterim列表的目的是可以更改列表,而字符串(如前所述)是不可变的。

Do you need to do it in a loop? 您是否需要循环执行? Otherwise, try string slicing: 否则,请尝试字符串切片:

word = raw_input("Enter your string: ")
amount = int(raw_input("Enter your amount: "))

s = word[0:amount]

No loops necessary! 无需循环!

word = raw_input("Enter your string:")
amount = int(raw_input("Enter your amount:"))

word = word[:amount]
print word

The first step is to read in your values, and cast the amount to an integer. 第一步是读取您的值,然后将金额转换为整数。 And since strings are lists of characters at heart, you can get sublists from them. 而且由于字符串是本质上的字符列表,因此您可以从中获取子列表。 In Python, the [x:y] notation gets a sublist from a list, on the interval [x, y). 在Python中, [x:y]表示法以间隔[x,y)从列表中获得一个子列表。 If you do not provide x ( [:y] ), the interval becomes [0, y); 如果不提供x( [:y] ),则间隔变为[0,y); if you don't provide y ( [x:] ): [x, len(theStr)); 如果不提供y( [x:] ):[x,len(theStr)); and if you don't provide either ( [:] ), you get the original string! 并且如果您都不提供( [:] ),则会得到原始字符串!

Bonus Fun Facts: 奖励趣闻:

The [x:y] operator is an extension of the array subscript operator, [x] . [x:y]运算符是数组下标运算符[x]的扩展。 In most languages, calling list[x] will give you the element at x. 在大多数语言中,调用list[x]将为您提供x处的元素。 However, in Python, it can behave more like a traversal. 但是,在Python中,它的行为更像遍历。 For example, list[-1] will give you the last element in the list. 例如, list[-1]将为您提供列表中的最后一个元素。

The [x:y:z] operator also exists, where z is the step interval to use during the traversal. [x:y:z]运算符也存在,其中z是遍历期间要使用的步长间隔。 Useful cases for this operator include getting elements at even indices ( list[::2] ), and reversing the list ( list[::-1] ). 对于此运算符,有用的情况包括获取偶数索引处的元素( list[::2] )和反转列表( list[::-1] )。

You may take help of slicing 您可以帮忙切片

word = raw_input("Enter your string:")
amount = raw_input("Enter your amount:")
word=word[:int(amount)]   #slicing the rest of unwanted characters
print word

Removing characters from a string in Python is difficult. 在Python中很难从字符串中删除字符。 A better way to approach the given problem would be either with slices, as others have suggested, or if you have to use a loop, by collecting the characters you need in a new string instead of removing them from the old one, ie 解决给定问题的更好方法是像其他人建议的那样使用切片,或者如果必须使用循环,通过将所需的字符收集到新字符串中,而不是从旧字符串中删除它们,即

s = raw_input()
n = int(raw_input())
new_s = ""
for i in range(n):
    new_s = new_s + s[i]

I guess you have two approaches 我想你有两种方法

  1. Create a new string adding chars one by one from the old until you reach your limit 创建一个新字符串,将旧字符一一添加,直到达到极限
  2. Overwriting the old string using a slice of itself [:-1] until you reach your limit 使用自身的一部分[:-1]覆盖旧字符串,直到达到极限

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

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