Reputation: 43
I have written some code in python and I got the problem that when I have for example a sentence "This is my very first python program", after using the split
function I get a result like this:
['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']
Now I want to pass each word separated with + signs into a url.
I would like to use a for each loop but my problem is that it should automatically replace it as I stated above.
For example, the result of "python program"
should be "python+program"
.
So can anyone tell me how to solve this problem in python?
Upvotes: 1
Views: 95
Reputation: 336428
How about this:
>>> a = "this is my first Python program"
>>> "+".join(a.split())
'this+is+my+first+Python+program'
Upvotes: 2
Reputation: 99660
This should work
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
Upvotes: 1
Reputation: 32094
It is better to use the right tool. What you need is to urlencode the text parameter, so you will need to use urllib.urlencode
function.
Upvotes: 3