我想获取字符串中第一个不可打印字符的索引,以便我可以用新字符替换它。
例如:
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/