从ID列表中删除单引号 [英] Removing the single quote from a list of ids

查看:140
本文介绍了从ID列表中删除单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为API调用附加ID/ID列表格式的URL.

I need to append/format a URL with a list of ids for an API call.

但是,当我将列表放在API的末尾时:

However, when I put the list at the end of the API:

https://api.twitter.com/1.1/users/lookup.json?user_id=%s'%a

我只是得到一个空字符串作为响应.

I just get an empty string as a response.

我尝试过将列表变成字符串并删除方括号,方法是:

I have tried turning the list into a string and removing the square brackets, doing:

a = str(followers['ids'])[1:-1]

但是我仍然遇到同样的问题.我假设这是由一开始的单引号引起的.

but I still get the same problem. I'm assuming that it's being caused by the single quote at the start.

我尝试过从字符串中删除撇号:

I have tried removing the apostrophe from the string doing:

a.replace("'", "")

现在我的想法已经用光了.

and now I have run out of ideas.

推荐答案

我尝试过从字符串中删除撇号...

您可以使用s = s.replace("'", "")从字符串中删除撇号. .replace() 返回一个新字符串,但不会更改原始字符串,因此您将可以存储返回的字符串.

You can remove apostrophe from a string using s = s.replace("'", ""). .replace() returns a new string but does not change the orginal string so you'll to store the returned string.

>>> string = "he's a jolly good fellow"
>>> string = string.replace("'", "") 
>>> string
'hes a jolly good fellow'

但是我不认为这不是您的问题.

id必须用逗号分隔,因此您可能需要使用 .join() 从ID列表中创建字符串.示例:

The ids need to be comma separated, so you'll probably want to use a .join() to create the string from your list of ids. Example:

>>> ids = ["1", "23", "123"]
>>> ",".join(ids)
'1,23,123'

在您的情况下,假设followers['ids']包含ID的字符串列表,则可以使用以下方法生成URL:

In your case, assuming followers['ids'] contain a list of id as strings, you can generate your URL using:

ids = ",".join(followers['ids'])  # generate string of ids (comma separated)
url = "https://api.twitter.com/1.1/users/lookup.json?user_id=%s" % ids

如果followers['ids']是整数列表而不是字符串,则还有很多工作要做,因为.join()仅适用于字符串序列.这是一种将这些整数即时转换为字符串的方法(使用生成器表达式):

If followers['ids'] is a list of integers instead of string, then there's a little more work to do since .join() works only with a sequence of strings. Here's one way to convert those integers to string on the fly (using a generator expression):

ids = ",".join(str(id) for id in followers['ids'])

这篇关于从ID列表中删除单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆