gpt4 book ai didi

python - 我如何在python上找到第一个路径空白的索引

转载 作者:行者123 更新时间:2023-12-03 08:17:56 24 4
gpt4 key购买 nike

我正在编写一个函数,该函数可以找到字符串的第一行空白的索引,但是我不确定该怎么做,有人可以教我吗?

例如“我在这里”。句子后面有三个空格。该功能将给我“10”。

输入的内容是一个文本python文件,该文件被分成句子(字符串列表)

这就是我尝试过的

alplist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] 
space = [' ', ',', '.', '(', ')', ':', ':']

def TRAIL_WHITESPACE(python_filename):
whitespace = []
LINE_NUMBER = 1
index = 0
for item in lines:
for index in range(len(item)):
if len(item) > 0:
if item[index] + item[index + 1] in alplist + space:
index = index
if item[index:] in " ":
whitespace.append({'ERROR_TYPE':'TRAIL_WHITESPACE', 'LINE_NUMBER': str(LINE_NUMBER),'COLUMN': str(index),'INFO': '','SOURCE_LINE': str(lines[ len(item) - 1])})
LINE_NUMBER += 1
else:
LINE_NUMBER += 1
else:
LINE_NUMBER += 1
else:
LINE_NUMBER += 1
return whitespace

谢谢

最佳答案

这可以使用str.rstrip()方法轻松完成:

#! /usr/bin/env python

#Find index of any trailing whitespace of string s
def trail(s):
return len(s.rstrip())

for s in ("i am here. ", "nospace", " no trail", "All sorts of spaces \t \n", ""):
i = trail(s)
print `s`, i, `s[:i]`

输出
'i am here. ' 10 'i am here.'
'nospace' 7 'nospace'
' no trail' 12 ' no trail'
'All sorts of spaces \t \n' 19 'All sorts of spaces'
'' 0 ''

关于python - 我如何在python上找到第一个路径空白的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26570015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com