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

标签 python string trailing chomp leading-zero

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

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

删除尾随零的期望输出是:

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

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

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

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

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

目前我一直在这样做,如果有,请提出更好的方法:

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 仅用于前导零)。

更多信息见 doc.

你可以使用一些列表推导来获得你想要的序列:

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]

关于python - 如何删除字符串中的前导零和尾随零? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13142347/

相关文章:

python - 有时 pip install 很慢

ios - NSMutableAttributedString 作为 UIAlertAction 的标题 - Swift

http-headers - 是否有浏览器支持以分块编码响应发送的预告片?

根据 R 中的另一列删除字符串的一部分

ORACLE TRIM 和 RTRIM : the TRIM (TRAILING… ) select with more than one character?

python - 在 bash 脚本中间使用父目录 ".."规范化路径

python - pip freeze 命令输出中的 "pkg-resources==0.0.0"是什么

python - 嵌入Python线程安全

使用 cout << 打印字符串时 CodeBlocks 中的 C++ 运行时错误