Python按索引删除部分字符串 [英] Python Remove Parts of string by index

查看:55
本文介绍了Python按索引删除部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串

string='texttexttextblahblah",".'

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

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

解决方案

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

<预><代码>>>>string='texttexttextblahblah',".'>>>字符串 = 字符串[:-3]>>>细绳'texttexttextblahblah''>>>

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

除非您确切知道您将拥有多少 textblah,否则请按照 Brent 的建议使用 .find()(或.index(x),与 find 类似,除了在找不到 x 时会抱怨).

如果你想要尾随的 ",只需在它踢出的值上加一个.(或者只是 find 你真正想要分割的值,,)

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

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 string so that string will be equal to texttexttextblahblah"

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

解决方案

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

Unless you know exactly how many text and 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).

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

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

这篇关于Python按索引删除部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆