Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串条_Python_String_Strip - Fatal编程技术网

Python字符串条

Python字符串条,python,string,strip,Python,String,Strip,我试图使用strip()删除一些HTML的结尾。我们的想法是最终将其构建成一个循环,但目前我只是想弄清楚如何使其工作: httpKey=("<a href=\"http://www.uaf.edu/academics/degreeprograms/index.html>Degree Programs</a>") httpKeyEnd=">" #the number in the httpKey that the httpKey end is at stripNum

我试图使用strip()删除一些HTML的结尾。我们的想法是最终将其构建成一个循环,但目前我只是想弄清楚如何使其工作:

httpKey=("<a href=\"http://www.uaf.edu/academics/degreeprograms/index.html>Degree Programs</a>")
httpKeyEnd=">"

#the number in the httpKey that the httpKey end is at
stripNumber=(httpKey.find(httpKeyEnd))
#This is where I am trying to strip the rest of the information that I do not need. 
httpKey.strip(httpKey.find(httpKeyEnd))
print (httpKey)
httpKey=(“”)
httpKeyEnd=“>”
#httpKey末端所在的httpKey中的数字
stripNumber=(httpKey.find(httpKeyEnd))
#这就是我试图剥离其余我不需要的信息的地方。
httpKey.strip(httpKey.find(httpKeyEnd))
打印(httpKey)
最终结果是仅使用以下命令将httpKey打印到屏幕:

a href=”http://www.uaf.edu/academics/degreeprograms/index.html


find
将返回找到字符串的索引(一个数字),而
strip
将删除字符串末尾的字符;它不会删除“从该点向前的所有内容”

您想改用字符串切片:

>>> s = 'hello there: world!'
>>> s.index(':')
11
>>> s[s.index(':')+1:]
' world!'
如果您只想知道链接是什么,请使用以下库:

>>从bs4导入BeautifulSoup作为bs
>>>doc=bs(“”)
>>>对于文档中的链接,查找所有('a'):
…打印(link.get('href'))
...
http://www.uaf.edu/academics/degreeprograms/index.html

对于您的案例,这将起作用:

>>> httpKey=("<a href=\"http://www.uaf.edu/academics/degreeprograms/index.html>Degree Programs</a>")
>>> httpKey[1:httpKey.index('>')]
'a href="http://www.uaf.edu/academics/degreeprograms/index.html'
>>httpKey=(“”)
>>>httpKey[1:httpKey.index('>')]
'a href='http://www.uaf.edu/academics/degreeprograms/index.html'

你的最终目标是什么?您正在尝试提取href吗?如果是这样的话,通过使用HTML解析库,您的生活将变得更加轻松。是的,这就是我们的目标。但是,这是我正在做的家庭作业,只能使用字符串操作。好的,下一个问题:href后面没有结束引号是故意的,还是打字错误?这是故意的,我现在正试图将httpKey设置为字符串。我想我可以写httpKey=str(“),这样就可以在字符63之前切片所有内容,在字符63之后不需要任何内容。
>>> httpKey=("<a href=\"http://www.uaf.edu/academics/degreeprograms/index.html>Degree Programs</a>")
>>> httpKey[1:httpKey.index('>')]
'a href="http://www.uaf.edu/academics/degreeprograms/index.html'