Python按索引删除部分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3516571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:30:36  来源:igfitidea点击:

Python Remove Parts of string by index

pythonstring

提问by Brian

I have a string

我有一个字符串

string='texttexttextblahblah",".'

and what I want to do is cut of some of the rightmost characters by indexing and assign it to stringso that stringwill be equal to texttexttextblahblah"

我想要做的是通过索引剪切一些最右边的字符并将其分配给它,string以便string等于texttexttextblahblah"

I've looked around and found how to print by indexing, but not how to reassign that actual variable to be trimmed.

我环顾四周,发现如何通过索引进行打印,但没有找到如何重新分配要修剪的实际变量。

采纳答案by Nick T

Just reassign what you printed to the variable.

只需将您打印的内容重新分配给变量即可。

>>> string='texttexttextblahblah",".'
>>> string = string[:-3]
>>> string
'texttexttextblahblah"'
>>>

Also, avoid using names of libraries or builtins (string) for variables

此外,避免使用库名称或内置函数 ( string) 作为变量

Unless you know exactly how many textand blah's you'll have, use .find()as Brent suggested (or .index(x), which is like find, except complains when it doesn't find x).

除非您确切知道您将拥有多少个textblah's,否则请.find()按照 Brent 建议的方式使用(或者.index(x),就像 find 一样,除非在没有 find 时抱怨x)。

If you want that trailing ", just add one to the value it kicks out. (or just findthe value you actually want to split at, ,)

如果您想要尾随",只需在它踢出的值上加一个。(或者只是find您实际想要拆分的值,,

mystr = mystr[:mystr.find('"') + 1]

回答by Brent Writes Code

Strings are immutable so you can't really change the string in-place. You'll need to slice out the part you want and then reassign it back over the original variable.

字符串是不可变的,因此您无法真正就地更改字符串。您需要切出所需的部分,然后将其重新分配回原始变量。

Is something like this what you wanted? (note I left out storing the index in a variable because I'm not sure how you're using this):

这是你想要的吗?(请注意,我没有将索引存储在变量中,因为我不确定您是如何使用它的):

>>> s = 'texttexttextblahblah",".'
>>> s.index('"')
20
>>> s = s[:20]
>>> s
'texttexttextblahblah'

回答by John La Rooy

If you needsomething that works like a string, but is mutableyou can use a bytearray

如果您需要像字符串一样工作但可变的东西,您可以使用字节数组

>>> s=bytearray('texttexttextblahblah",".')
>>> s[20:]=''
>>> print s
texttexttextblahblah

bytearray has all the usual string methods

bytearray 具有所有常用的字符串方法

回答by Tony Veijalainen

I myself prefer to do it without indexing: (My favorite partition was commented as winner in speed and clearness in comments so I updated the original code)

我自己更喜欢在没有索引的情况下进行:(我最喜欢的分区在评论中被评论为速度和清晰度方面的赢家,所以我更新了原始代码)

s = 'texttexttextblahblah",".'
s,_,_ = s.partition(',')
print s

Result

结果

texttexttextblahblah"