python - 获取Python中第一个不可打印字符的索引

标签 python

我想获取字符串中第一个不可打印字符的索引,以便我可以用新字符替换它。

例如: indexNonPrintable(" hell [不可打印]世界!") = 4

如果可能的话,我想在 python 中以优化的方式完成它,否则我可以这样做:

i = 0    
for c in str:
   if (c not in string.printable)
      return i
   i = i + 1

最佳答案

只是为了好玩,一句台词:

def indexNonPrintable(s):
    return next(i for i, x in enumerate(s) if x not in string.printable)

如果不存在不可打印的字符,该版本将引发 StopIteration ;您可以将其更改为:

    return next((i for i, x in enumerate(s) if x not in string.printable), None)

失败时返回None(或使用-1表现得像str.find),或者:

    try:
        return next(i for i, x in enumerate(s) if x not in string.printable)
    except StopIteration:
        raise ValueError("No non-printable characters found")

行为类似于str.index,并在未找到匹配字符时引发ValueError

关于python - 获取Python中第一个不可打印字符的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070146/

相关文章:

Python:如何从 __init__.py 文件导入?

python - NetworkX 多向图可能吗?

python - 迭代 Pandas DataFrame 的行 - 根据另一个系列中的值更改系列值?

Python:列表列表到字典

python - 如何在 python 中压缩两个元组列表

python - 如何让 pip3 在 Linux 上运行

python - 为什么耗尽的生成器不止一次引发 StopIteration?

Python点击: handling cli usage Exceptions in a chained MultiCommand with context resource

python - 字典理解索引错误

python - 在 Scikit-learn 分类器中找到最常见的术语