繁体   English   中英

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

[英]Get Index of the first non printable character in Python

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

例如: indexNonPrintable("Hell[nonprintable] World!") = 4

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

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

只是为了funsies,单线:

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

我会使用正则表达式。 像这样的东西可能会起作用:

import re
import string

match = re.search('[^' + re.escape(string.printable) + ']', str)
if match:
    return match.start()

你可以使用ord(c)将每个字符转换为ascii。

i = 0    
for c in str:
   ascii_c = ord(c)
   if ascii in range(x,y)
      return i
   i = i + 1

其中x和y是ascii值表中字符的整数值

暂无
暂无

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

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