簡體   English   中英

在Python中替換列表中的單引號

[英]Replace single quotes from list in 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但無法進行其他替換。

有什么方便的方法可以做到這一點嗎?

在您的示例中,您使用的是列表表示形式,其中包括方括號和引號,引號不在字符串本身中,而是在列表的表示形式中,當您將Python包含在另一個帶有.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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM