替换列表

时间:2018-02-15 21:57:39

标签: python-3.x

我在python中创建了一个Google搜索器。有没有办法可以用" +"替换列表中的空格?为我的网址?到目前为止,这是我的代码:

q=input("Question=")
qlist=list(q)
#print(qlist)

我可以用加号替换列表中的任何空格,然后将其转换回字符串吗?

3 个答案:

答案 0 :(得分:1)

只想在此添加另一条思路。尝试使用urllib库来解析URL字符串。

这是一个例子:

import urllib

## Create an empty dictionary to hold values (for questions and answers).
data = dict()

## Sample input
input = 'This is my question'

### Data key can be 'Question'
data['Question='] = input

### We'll pass that dictionary hrough the urlencode method
url_values = urllib.parse.urlencode(data)

### And print results
print(url_values)

#-------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------
#Alternatively, you can setup the dictionary a little better if you only have a couple of key-value pairs

## Input
input = 'This is my question'

# Our dictionary; We can set the input value as the value to the Question key
data = {
    'Question=': input
    }

print(urllib.parse.urlencode(data))

输出:

'Question%3D=This+is+my+question'

答案 1 :(得分:0)

您可以将它们连接在一起以创建1个长字符串。

qlist = my_string.split(" ")
result = "+".join(qlist)
print("Output string: {}".format(result))

答案 2 :(得分:0)

查看python中的join和split操作。

q = 'dog cat'
list_info = q.split()

https://docs.python.org/3/library/stdtypes.html#str.split

q = ['dog', 'cat']
s_info = ''.join(q)

https://docs.python.org/3/library/stdtypes.html#str.join