2016-09-23 123 views
-1

我有一個字符串test_file1。如果他/她輸入的字符串以'test'開頭,我想檢查用戶輸入的字符串。如何在Python中做到這一點? 讓ARGS是= [ 'test_file裏面']查看單詞開頭爲特定字母python

for suite in args: 
      if suite.startswith('test'): 
       suite="hello.tests."+suite 
      print(suite) // prints hello.tests.test_file 
print(args) //prints ['test.file]' and not ['hello.tests.test_file'] 
+0

它應該工作,另外,請參見[MCVE] – Lafexlos

+2

您可以發佈您的代碼? – Don

+0

爲什麼startswith不起作用?你能解釋 – armak

回答

0

你可以使用正則表達式。

pat = re.compile(r'^test.*') 

那麼你可以使用這種模式來檢查每一行。

+0

應在'*' – Don

+1

之前放置一個點'.' @你是對的 – armak

1

只需使用:

String.startswith(str, beg=0,end=len(string)) 

在你的情況,這將是

word.startswith('test', 0, 4) 
+0

在這種情況下是否需要'beg'和'end'? – Don

+0

@唐:參考:https://www.tutorialspoint.com/python/string_startswith.htm –

+0

Thanx!我不知道那些參數。但應該是'str.startswith'而不是'String.startswith' – Don

0

問題的代碼是你是不是有新的創造套件名稱替換的args列表的套件。

檢查了這一點

args = ['test_file'] 
print "Before args are -",args 
for suite in args: 
    #Checks test word 
    if suite.startswith('test'): 
     #If yes, append "hello.tests" 
     new_suite="hello.tests."+suite 
     #Replace it in args list 
     args[args.index(suite)]=new_suite 

print "After args are -",args 

輸出:

C:\Users\dinesh_pundkar\Desktop>python c.py 
Before args are - ['test_file'] 
After args are - ['hello.tests.test_file'] 

C:\Users\dinesh_pundkar\Desktop> 

以上可以使用列表理解也執行。

args = ['test_file',"file_test"] 
print "Before args are -",args 

args = ["hello.tests."+suite if suite.startswith('test') else suite for suite in args] 

print "After args are -",args 
相關問題