如何删除字符串中的前导零和尾随零? Python

问题描述:

我有几个这样的字母数字字符串

I have several alphanumeric strings like these

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']

用于删除后缀零的理想输出为:

The desired output for removing trailing zeros would be:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']

前导尾随零的期望输出为:

The desired output for leading trailing zeros would be:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']

同时删除前导零和尾随零的期望输出为:

The desire output for removing both leading and trailing zeros would be:

listOfNum = ['231512-n','1209123100000-n', 'alphanumeric', 'alphanumeric']

目前,我一直按照以下方式进行操作,如果有的话,请提出一种更好的方法:

For now i've been doing it the following way, please suggest a better way if there is:

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \
'000alphanumeric']
trailingremoved = []
leadingremoved = []
bothremoved = []

# Remove trailing
for i in listOfNum:
  while i[-1] == "0":
    i = i[:-1]
  trailingremoved.append(i)

# Remove leading
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  leadingremoved.append(i)

# Remove both
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  while i[-1] == "0":
    i = i[:-1]
  bothremoved.append(i)

基本情况如何

your_string.strip("0")

同时删除尾随零和前零?如果您只想删除尾随零,请改用.rstrip(仅.lstrip用于前导零).

to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

[文档中的更多信息.]

[More info in the doc.]

您可以使用一些列表推导来获得所需的序列,如下所示:

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]