Python检查字符串是否有某个单词(或字符组合)

时间:2016-10-06 16:24:24

标签: python python-3.x

好的,我有这个字符串(例如):

<?php include 'connection.php';?>
<?php
if(isset($_POST['search'])){
    if(count($_FILES['upload']['name']) > 0){
        echo "OhhYESHOOO";
        //Loop through each file
        for($i=0; $i<count($_FILES['upload']['name']); $i++) {
          //Get the temp file path
            $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
            echo "HERE";

            //Make sure we have a filepath
            if($tmpFilePath != ""){
            echo "Entered";
                //save the filename
                $shortname = $_FILES['upload']['name'][$i];
                //echo "*$shortname";
                //save the url and the file
                $filePath = "uploaded/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];

                //Upload the file into the temp dir
                if(move_uploaded_file($tmpFilePath, $filePath)) {
                    echo "Entered Again";
                    $files[] = $shortname;
                    //insert into db 
                    //use $shortname for the filename
                    //use $filePath for the relative url to the file

                }
              }
        }
    }

    //show success message
    echo "<h1>Uploaded:</h1>";    
    if(is_array($files)){
        echo "<ul>";
        foreach($files as $file){
            echo "<li>$file</li>";
        }
        echo "</ul>";
    }
}
?>

我想做的是检查该字符串是否包含&#34; ea&#34;。

4 个答案:

答案 0 :(得分:1)

使用word in sentence。例如:

>>> 'el' in 'Hello'
True
>>> 'xy' in 'Hello'
False

供您参考,请检查:cppreference

答案 1 :(得分:1)

简单:

>>> var = "I eat breakfast."
>>> 'ea' in var
True

我不清楚“将这些值放入列表中”是什么意思。我猜你的意思是:

>>> [w for w in var.split() if 'ea' in w]
['eat', 'breakfast.']

答案 2 :(得分:1)

这是Finding multiple occurrences of a string within a string in Python

的副本

你可以这样使用find(str, startIndex)

var = "I eat breakfast."

locations = []
index = 0
while index < len(var):
  index = var.find('ea', index)
  if index == -1:
    break
  locations.append(index)
  index += 2

locations是找到'ea'的索引列表。

答案 3 :(得分:0)

您可以使用in检查字符串是否包含子字符串。如果它包含子字符串,您还希望将var添加到列表中。观察以下交互式会话:

In [1]: var = "I eat breakfast."

In [2]: lst = []

In [3]: if "ea" in var:
   ...:     lst.append(var)
   ...:     

In [4]: lst
Out[4]: ['I eat breakfast.']