简体   繁体   中英

How to remove double quotes from list of strings?

VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = []
for item in VERSION:
    temp = item.replace('"','')
    VERSIONS_F.append(temp)
    print (VERSIONS_F)

In the above block of code VERSIONS_F is also printing the same ["'pilot-2'", "'pilot-1'"] , but I would need something like ['pilot-2', 'pilot-1'] . I even tried strip('"') and am not seeing what I want.

You can do this in a couple of lines:

VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = [item [1:-1] for item in VERSION]
print(VERSIONS_F)

OUTPUT:

['pilot-2', 'pilot-1']

This way simply slices the first and last character from the string, which assumes that the "" are always at the first and last position.

Note: Grismar gives a good overview of what is happening under the hood as well

When you print a list, Python will print the representation of the list, so the strings inside of the list are not printed like a string normally is:

>>> print('hello')
hello

Compared to:

>>> print(['hello'])
['hello']

Adding different quotes will cause Python to select the opposite quotes to represent the string:

>>> print(['\'hello\''])
["'hello'"]
>>> print(["\"hello\""])
['"hello"']

Beginning Python programmers often make the mistake of confusing what is printed on the console with an actual value. print(x) doesn't show you the actual value of x (whatever that may be), but its text string representation.

For example:

>>> x = 0xFF
>>> print(x)
255

Here, a value is assigned as its hexadecimal representation, but of course the actual value is just 255 (in decimal representation) and the decimal representation is the standard representation chosen when printing an integer value.

The 'real' value of the variable is an abstract numerical value, choices made when representing it don't affect that.

In your case, you defined the strings as having single quotes as part of the string using VERSION = ["'pilot-2'", "'pilot-1'"] . So, if you want to remove those single quotes, you could:

VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = []
for item in VERSION:
    temp = item.replace("'",'')
    VERSIONS_F.append(temp)
    print (VERSIONS_F)

Result:

['pilot-2']
['pilot-2', 'pilot-1']

Or, more simply:

VERSIONS_F = [v.strip("'") for v in VERSION]

In response to the comment:

VERSION = ["'pilot-2'", "'pilot-1'"]
temp_list = ['pilot-1', 'test-3']

print(any(x in [v.strip("'") for v in VERSION] for x in temp_list))

Try this:

VERSION = ["'pilot-2'", "'pilot-1'"]
VERSIONS_F = []
for item in VERSION:
  temp = item.replace("'",'')
  VERSIONS_F.append(temp)
print (VERSIONS_F)

it will print ['pilot-2','pilot-1']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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