Python 检查单词以特定的字母开始

Python 检查单词以特定的字母开始,python,Python,我有一个字符串测试文件1。我想检查从用户处获取字符串时,他/她输入的字符串是否以“test”开头。如何在python中实现这一点? 设args为=['test_file'] for suite in args: if suite.startswith('test'): suite="hello.tests."+suite print(suite) // prints hello.tests.test_file pri

我有一个字符串测试文件1。我想检查从用户处获取字符串时,他/她输入的字符串是否以“test”开头。如何在python中实现这一点? 设args为=['test_file']

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']
您可以使用正则表达式

pat = re.compile(r'^test.*')
然后您可以使用此模式检查每一行。

只需使用:

String.startswith(str, beg=0,end=len(string))
以你的情况来说,那将是

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

代码的问题是您没有用新创建的套件名称替换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

它应该也能工作,请看你能发布你的代码吗?为什么startswith不能工作??你能解释一下吗?好的,我正在更改列表中的一个字符串,它的修改开始生效,但是最后的列表显示字符串没有任何更改。我做了有问题的编辑。一个点
应该放在
*
之前,在这种情况下需要
beg
end
吗?Thanx!我不认识那些情妇。但是应该是
str.startswith
而不是
String.startswith