简体   繁体   English

如何从字符串中去除尾随数字

[英]How to strip trailing digits from a string

I have a variable text whose value is like below,I need strip of trailing digits,is there a python built-in function to do it..if not,please suggest how can this be done in python我有一个变量文本,其值如下所示,我需要一些尾随数字,是否有 python 内置函数来执行它..如果没有,请建议如何在 python 中完成

eg -text=A8980BQDFZDD1701209.3 => -A8980BQDFZDD例如-text=A8980BQDFZDD1701209.3 = -text=A8980BQDFZDD1701209.3 => -A8980BQDFZDD

In [36]: myStr = '-text=A8980BQDFZDD1701209.3'

In [37]: print '-'+myStr.rpartition('=')[-1].rstrip('1234567890.')
-A8980BQDFZDD

For the sake of completion, how about this syntax in python3 ?为了完成,python3中的这个语法怎么样?

from string import digits

print('123abc382'.rstrip(digits))
print '123abc382'.rstrip('1234567890')
print 'text=A8980BQDFZDD1701209.3'.rstrip('1234567890.')[5:]

will do everything required.会做所有需要的事情。 The slicing at the end is something of a hack, however.然而,最后的切片有点像黑客。

The first step is to understand what information the strings are encoding, and how you decode it as you read it.第一步是了解字符串正在编码哪些信息,以及如何在阅读时对其进行解码。 That tells you what the patterns in your data are, and those will determine how you'll manipulate the string to extract the information in Python.这会告诉您数据中的模式是什么,这些模式将决定您将如何操作字符串以在 Python 中提取信息。

If you just need to lose the last few numbers, you could rstrip them easily enough.如果你只是需要减肥的最后几个数字,你可以rstrip他们很轻松了。 This is assuming you want to change "-text=" to "-", as you imply in the question:这是假设您想将“-text=”更改为“-”,正如您在问题中暗示的那样:

input = '-text=A8980BQDFZDD1701209.3'
text = input.split('=')[1]
output =  '-' + text.rstrip('1234567890.')

This is a potentially risky approach since it also assumes the numeric suffix will never have any alphabetic characters in it, and that the half you want to keep will never end in a character you're passing to rstrip .这是一种潜在的风险方法,因为它还假定数字后缀中永远不会包含任何字母字符,并且您想要保留的一半永远不会以您传递给rstrip的字符rstrip If either of those things are not always true of your data, this solution will give you bad results and you'll need to find a more accurate pattern.如果这些事情中的任何一个对您的数据并不总是正确的,则此解决方案会给您带来糟糕的结果,您需要找到更准确的模式。

For example, if the 'keep' part is always 12 characters long, you would want to take a string slice by replacing line 3 of my example with this:例如,如果 'keep' 部分的长度总是12 个字符,您可能希望通过将示例的第 3 行替换为一个字符串切片:

output = '-' + text[:12]

But ultimately, it depends on what these strings are, and what rules define how the different halves are formed in the first place.但最终,这取决于这些字符串是什么,以及首先定义不同部分如何形成的规则。

You can use rstrip .您可以使用rstrip Check the python docs.检查 python 文档。

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

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