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

alv*_*vas 91 python string trailing chomp leading-zero

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

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']
Run Code Online (Sandbox Code Playgroud)

删除尾随零的所需输出将是:

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']
Run Code Online (Sandbox Code Playgroud)

前导尾随零的所需输出为:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
Run Code Online (Sandbox Code Playgroud)

删除前导零和尾随零的欲望输出将是:

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
Run Code Online (Sandbox Code Playgroud)

现在我一直按照以下方式进行,如果有以下情况,请建议更好的方法:

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)
Run Code Online (Sandbox Code Playgroud)

Pie*_* GM 200

什么是基本的

your_string.strip("0")
Run Code Online (Sandbox Code Playgroud)

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

[更多信息在文档中 ]

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

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]
Run Code Online (Sandbox Code Playgroud)

  • 对于`s = '0'`的特殊情况,这个答案是否有任何巧妙的调整? (3认同)
  • @查尔斯:是的!我只是遇到了同样的问题,您可以执行s.strip(“ 0”)或“ 0”`:如果您的字符串变成空字符串,则它的计算结果为False或由替换为所需的字符串“ 0” (2认同)

fho*_*fho 14

删除前导+尾随'0':

list = [i.strip('0') for i in listOfNum ]
Run Code Online (Sandbox Code Playgroud)

删除前导'0':

list = [ i.lstrip('0') for i in listOfNum ]
Run Code Online (Sandbox Code Playgroud)

删除尾随'0':

list = [ i.rstrip('0') for i in listOfNum ]
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以简单地通过bool做到这一点:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)
Run Code Online (Sandbox Code Playgroud)

  • 无法按OP要求与`alphanumeric0000`配合使用。 (2认同)