在Python中替换列表中的单引号

2024-04-27 16:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在查询bigquery以获取其模式,该模式返回下面的列表

['word STRING', 'word_count INTEGER', 'corpus STRING', 'corpus_date INTEGER']

在这个输出列表中,我尝试使用下面的代码将单引号替换为空,INTEGER替换为BIGINT。你知道吗

# Output from the query    
result = ['word STRING', 'word_count INTEGER', 'corpus STRING', 'corpus_date INTEGER']
result_new = [string.replace("INTEGER", "BIGINT").replace("'", "") for string in result]
result_new = 'create table {} {} stored as orc;'.format(table_id, result_new)
print(result_new) 

其返回结果为:

create table shakespeare ['word STRING', 'word_count BIGINT', 'corpus STRING', 'corpus_date BIGINT'] stored as orc;

我想要的输出是:

create table Shakespeare (word STRING, word_count BIGINT, corpus STRING, corpus_date BIGINT) stored as orc;

因为我对Python完全陌生,所以我在google上搜索并尝试了很多东西,但正在将INTEGER替换为BIGINT,但不打算替换其他东西。你知道吗

有什么方便的方法来完成这件事吗?你知道吗


Tags: newdatestringascountcreatetable模式
1条回答
网友
1楼 · 发布于 2024-04-27 16:08:50

在您的示例中,您使用的是列表表示法,它包括方括号和引号,引号不在字符串本身中,而是在列表表示法中,当您使用.format将其包含在另一个字符串中时,python会自动生成。你知道吗

更好的方法是直接按照您想要的方式构建字符串:

result = ['word STRING', 'word_count INTEGER', 'corpus STRING', 'corpus_date INTEGER']
# turn integer into bigint
result = [x.replace('INTEGER', 'BIGINT') for x in result]
# join the strings in a single string using comma as separator:
result_new = ', '.join(result) 
sql = 'create table {} ({}) stored as orc;'.format(table_id, result_new)

相关问题 更多 >