替换列表中索引k后的每个单词

时间:2016-06-20 16:22:59

标签: python list python-2.7 replace

如何替换列表中索引[3]后的每个单词?

例如,我需要将第一个单词更改为“How's”,将第二个单词更改为“it”,将第三个单词更改为“going?”。然后,我需要在索引[3]之后将每个单词更改为“yo”:

namespace App\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

class ComposerCommand extends Command {

    /**
     * Configures the console Application
     *
     */
    protected function configure() {
        $this->setName("composer:install")
            ->setDescription("Composer install inside a symfony console.")
            ->addOption('path', 'p', InputOption::VALUE_REQUIRED)
            ->setHelp(<<<EOT
The <info>composer:install</info> command makes "composer install"
EOT
            );
    }

    /**
     * Executes the console Application
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @throws \Exception
     */
    protected function execute(InputInterface $input, OutputInterface $output) {
        try {
            $path = $input->getOption('path');

            $process = new Process('php composer.phar install --no-interaction');
            $process->setWorkingDirectory($path);
            $process->run();

            // executes after the command finishes
            if (!$process->isSuccessful()) {
                throw new ProcessFailedException($process);
            }

            $output->writeln($process->getOutput());
            $output->writeln($process->getErrorOutput());
        } catch (\Exception $e) {
            throw new \Exception($e);
        }

    }
}

这是我到目前为止所做的:

input = "My name is bla bla bla?" 

output = "How's it going? Yo! Yo! Yo!"

到目前为止我只得到:

def hellohello(input):
    if type(input) != str:
        return "Input has to be string"
    else:
        new_input = input.split(' ')
        if len(input) <= 3:
            return "How's it going?"
        else:
            new_input[0] = "How's "
            new_input[1] = "it "
            new_input[2] = "going? "
            new_input[3:] = ["Yo! "]
            output = ''.join(new_input)
            return output

print hellohello("why is this not printing more yo")

2 个答案:

答案 0 :(得分:2)

叫我懒惰,但我可能首先创建一个长度为len(new_input)的列表,其中包含'Yo!',然后交换["How's", "it", "going?"] ...

>>> s = "My name is bla bla bla?"
>>> new_input = s.split()
>>> output = ['Yo!'] * len(new_input)
>>> output[:3] = ["How's", "it", "going?"]
>>> output
["How's", 'it', 'going?', 'Yo!', 'Yo!', 'Yo!']

您的代码存在问题:

new_input[3:] = ["Yo! "]

您正在使用单个元素替换多个元素。您可以通过执行new_input[3:] = ["Yo! "] * (len(new_input) - 3)来修复代码,这将创建一个"Yo! "列表,其长度与您尝试替换的子列表的长度相同。

您可能已经注意到我使用的是s.split()而不是s.split(' ')s.split()s.split(None)相同,它在连续的空白行(包括换行符和制表符)上分割。基本上,'foo bar\tbaz'.split()会产生['foo', 'bar', 'baz'],而'foo bar\tbaz'.split(' ')会产生['foo', '', 'bar\tbaz']

答案 1 :(得分:1)

试试这个:

def hellohello(input):
    if type(input) != str:
        return "Input has to be string"
    else:
        new_input = input.split(' ')
        if len(input) <= 3:
            return "How's it going?"
        else:
            new_input[0] = "How's"
            new_input[1] = "it"
            new_input[2] = "going?"
            for currentIndex in xrange(3, len(new_input)):
                new_input[currentIndex] = "Yo!"
            output = ' '.join(new_input)
            return output

print hellohello("why is this not printing more yo")
print hellohello("why is this")
print hellohello("why is this yep")

输出:

How's it going? Yo! Yo! Yo! Yo!
How's it going?
How's it going? Yo!

通过执行new_input[3:] = ["Yo! "],您只需将所有字符串标记的子数组(在由split分隔的数组中)从索引3替换为具有单个字符串“Yo!”的最后一个索引,自己替换每个数组项。基本上,您引用了数组的整个切片(3:)而不是单个项目。

[编辑:基于正确评论的更新解决方案,不需要使用切片和索引计算,还添加了之前出错的解释]