2016-09-23 122 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 
相关问题