在python中将空格替换为+

时间:2013-04-06 20:19:58

标签: python

我已经在python中编写了一些代码,我遇到的问题是,当我有一个句子“这是我的第一个python程序”时,在使用split函数后,得到如下结果:< / p>

['this', 'is', 'my', 'very', 'first', 'python', 'program']
['this', 'is', 'my', 'very', 'first', 'python program']
['this', 'is', 'my', 'very', 'first python program']
['this', 'is', 'my', 'very first python program']
['this', 'is', 'my very first python program']
['this', 'is my very first python program']
['this is my very first python program']

现在我想将用+符号分隔的每个单词传递给一个网址。

我想为每个循环使用a但我的问题是它应该自动替换它,如上所述。

例如,"python program"的结果应为"python+program"

那么有谁能告诉我如何在python中解决这个问题?

3 个答案:

答案 0 :(得分:3)

最好使用正确的工具。您需要的是对文本参数进行urlencode,因此您需要使用urllib.urlencode函数。

答案 1 :(得分:2)

这个怎么样:

>>> a = "this is my first Python program"
>>> "+".join(a.split())
'this+is+my+first+Python+program'

答案 2 :(得分:1)

这应该有效

my_string = "this is my very first python program"
n = len(my_string.split(' '))
for i in range(n):
    my_string_split = [x.replace (" ", "+") for x in my_string.split(' ', n-i-1)]
    print my_string_split