简体   繁体   English

从字符串中删除开始和结束 " 并存储为变量

[英]Remove beginning and ending " from a string and store as variable

I have a simple python list below called lis我在下面有一个简单的 python 列表,称为 lis

    lis = ['CWA9','WQH0','GBD0']

When I print and slice the list, I get the format I desire, but cannot figure how to store as a variable当我打印和切片列表时,我得到了我想要的格式,但不知道如何存储为变量

    print (str(lis)[1:-1])

    'CWA9','WQH0','GBD0'

I tried the following, but I get the beginning and ending " marks (string format).我尝试了以下操作,但我得到了开始和结束的 " 标记(字符串格式)。

    str(lis)[1:-1]

    "'CWA9','WQH0','GBD0'"

Whats the best approach to format the original list (lis) to the format seen in the print code above so that the output is 'CWA9','WQH0','GBD0' and store as a variable将原始列表 (lis) 格式化为上面打印代码中所见格式的最佳方法是什么,以便 output 为“CWA9”、“WQH0”、“GBD0”并存储为变量

Updated: You can do更新:你可以做

lis = ['CWA9','WQH0','GBD0']
lis = [f"'{x}'" for x in lis] #New line in update
lis = ', '.join(lis)

then print(lis) gives然后print(lis)给出

'CWA9', 'WQH0', 'GBD0'

The double quotes are not part of the output. You can check it by:双引号不是 output 的一部分。您可以通过以下方式查看:

lis = ['CWA9','WQH0','GBD0']

a = str(lis)[1:-1]

a[0]

This will print:这将打印:

"'"

Which means your first character is actually the single quote.这意味着您的第一个字符实际上是单引号。 Double quotes are only printed to let you know it is a string.打印双引号只是为了让您知道它是一个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM