2016-09-23 4 views
-1

나는 test_file1이라는 문자열을 가지고 있습니다. 내가 입력 한 문자열이 'test'로 시작하면 사용자로부터 문자열을 가져 왔는지 확인하고 싶습니다. 어떻게 파이썬 에서이 작업을 수행 할 수 있습니까? 특정 알파벳으로 시작하는 단어 확인 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

당신이 정규식을 사용할 수 있습니다 [ 'test_file'] 인수가 =이 될 수 있습니다.

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

이 패턴을 사용하여 각 줄을 확인할 수 있습니다.

+0

'*'앞에'.'을 써야합니다. – Don

+1

@Don 당신이 맞습니다. – armak

1

는 간단히 사용 : 귀하의 경우

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

, 그것은 새로운 창조 스위트 이름으로 인수 목록에서 제품군을 교체하지 않을 것입니다 코드

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

이 경우에'beg'와'end'가 필요합니까? – Don

+0

@Don : 참조 : https://www.tutorialsp.com/.com/python/string_startswith.htm –

+0

고맙습니다. 나는 그 매개 변수를 몰랐다. 그러나'String.startswith'가 아닌'str.startswith'이어야합니다. – Don

0

문제가 될 수 있습니다.

확인이 밖으로

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 
그것은 작동합니다
관련 문제