简体   繁体   English

Python:检查输入的第一个字符

[英]Python : Check an inputs first characters

Okay so i have a problem i looked it up but didnt know exactly what to look up and kept seeing problems that had nothing to do with mine.. So my problem here is im taking an input in python 好的,所以我有一个问题我查了一下,但不知道到底要查什么,并一直看到与我无关的问题。所以我的问题是我在python中输入

flashSite = raw_input('[?] Please Provide a Web Url : ')

After it takes the input i want it to check if the http:// characters are included in the beginning of the input , if they are then dont add them in again , if they arent then add them in for the user , Help is greatly appreciated.. Also im new to Stackoverflow so i will have problems with little things like putting code in comments and such:( 在接受输入之后,我希望它检查输入的开头是否包含http://字符,如果不输入,则不要再次添加它们;如果没有,则为用户添加它们,帮助将非常有帮助赞赏..这也是Stackoverflow的新功能,因此我将遇到一些小问题,例如将代码放入注释等中:(

edit : So from other answers and comments i came out with this 编辑:所以从其他答案和评论中我得出了这个

def ScrapeFlashFiles():
flashSite = raw_input('Please Provide a web URL : ')
if flashSite.lower().startswith(flashSite, beg=0, end=7('http://')):
    return flashSite
elif flashSite.lower().startswith(flashSite, beg=0, end=4('www.')):
    flashSite = 'http://' + flashSite
print ' Sending requests... '
flashReq = requests.get(flashSite)
print ' Scraping content '
flashTree = html.fromstring(flashReq.content)
print 'Searching for keyword \'.swf\' '
for line in flashReq.content.split('\n'):
    if '.swf' in line:
        print line
print 'Flash Scrape Complete..'

Am i doing something wrong here? 我在这里做错什么了吗?

Note i am a beginner.. Im getting an error now talking about an int.. 注意我是一个初学者..我现在在谈论一个整数时出错。

Source to where i was reading about the startswith method https://www.tutorialspoint.com/python/string_startswith.htm 我正在阅读有关startswith方法的资源来源https://www.tutorialspoint.com/python/string_startswith.htm

raw_input returns a string, as visible from the documentation: https://docs.python.org/2/library/functions.html# raw_input返回一个字符串,从文档中可以看到: https : //docs.python.org/2/library/functions.html#

Since you're working with a string Type, you can use any of the string methods https://docs.python.org/2/library/stdtypes.html#string-methods . 由于您使用的是字符串类型,因此可以使用任何字符串方法https://docs.python.org/2/library/stdtypes.html#string-methods

For example: 例如:

expected_beginning = 'http://'
if not flashSite.startswith(expected_beginning):
  flashSite = expected_beginning + flashSite

You could do interesting things, like make sure it's always lowercase by doing: 您可以做一些有趣的事情,例如通过执行以下操作确保它始终为小写:

if not flashSite.lower().startswith(expected_beginning):

etc. 等等

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

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