how to convert single quotes list with double quotes list - python

I have a predefined list with single quotes and I want double quotes in each element.
for example, this is my predefined list
l = ['A','b']
the output I needed as the list only
l = ["A","b"]
I am trying with json but it is giving list as a string but I want list.
import json
l = ['A','b']
output = json.dumps(l)
print(type(output))

There is no difference in your case. Try to print l:
l_double = ["A","b"]
l_single = ['A','b']
print(l_double)
print(l_single)
returns
['A', 'b']
['A', 'b']
In case you really want double quotes around you list items, try something like this:
l = ['A','b']
l_real_double = [f'"{c}"' for c in l]
print(l_real_double)
which prints
['"A"', '"b"']

L = ['A', 'B', 'C']
print('[', end='') #just to print the opening third bracket [
for i in range(len(L)): #the variable i will assume the values from 0 to length of L - 1 i.e. the indices of the elements
print('"' + L[i] + '"', end='') #display a double quote and the string inside it
if i < len(L)-1:
print(',', end=' ') #if i is not the index of the last element then display a comma after it
print(']') #just to print the closing third bracket ]

Related

How would I reference something akin to an input more than once with list comp in Python?

For example, this simple code for outputting the middle character of a word - if it has a middle character.
string = str(input("String: "))
print(list(letter for letter in string if letter == string[((len(string) - 1) // 2)]))
Could I have the input inside of the list comp whilst still being able to reference the length of it in another part? Usually I do something like this with my inputs in list comp:
print(''.join(str(y) for y in [x for x in str(input("Please enter a string: "))
if x.isnumeric() == False]))
Just wanting to learn more about list comp's possibilities.
One approach is to store it inside its own list and unpack it using for
string = input("String: ")
would become
for string in [input("String: ")]
>>> print([letter for string in [input("String: ")] for letter in string if letter == string[(len(string) - 1) // 2]])
String: abcde
['c']
formatted over multiple lines:
>>> print(
... [letter for string in [input("String: ")]
... for letter in string
... if letter == string[(len(string) - 1) // 2]]
... )
Also, your logic may have undesired behaviour.
String: abcdecccccc
['c', 'c', 'c', 'c', 'c', 'c', 'c']
If I wanted to cram something like this onto one line I'd use a lambda:
>>> print((lambda x: x[(len(x) - 1) // 2])(input()))
middle
d
In this case I think readability is vastly improved by doing the variable assignment on its own line, though.

Python tKinter adds apostrophe to list

I'm working on an Python script with a GUI.
I can read out some colors using get().
The problem is that when I want to use these colors to draw shapes using PIL, Python adds apostrophes to the beginning and end of the list.
def add_color_lines():
the_color=tab_lines_colors_input.get()
lines_color_list.append(the_color)
print(lines_color_list)
This is the output:
'"white","black","grey"'
I want it to be:
"white","black","grey"
What am I doing wrong?
Why does the script add apostrophes to the list?
This is what I add:
This is what I get. Notice the apostrophes next to the brackets.
PIL cannot work with this because it says:
ValueError: unknown color specifier: '"white","black","grey"'
You can parse the string it's giving with the split() function.
output = lines_color_list.split(",")
This should output this list
['"white"', '"black"', '"gray"']
Alright, as mentioned by #acw1668 when you get the input form the text, it should just be color without quotes. white,black,grey
Now, in change the code to use the_color.split(",") and append that values to the list using lines_color_list += the_color.split(",")
lines_color_list = []
def add_color_lines():
global lines_color_list
the_color=tab_lines_colors_input.get()
lines_color_list += the_color.split(",")
print(lines_color_list)
The reason of apostrophe/single quote (') is how print function prints string elements of a list. Try this out to see how it prints.
Sample 1:
# Three elements in a list
my_list = ["a", "b", "c"]
print(my_list)
output
['a', 'b', 'c']
Sample 2:
# Three element in a list
my_list = ['a', 'b', 'c']
print(my_list)
output
['a', 'b', 'c']
Sample 3:
# One element in a list
my_list = ["a, b, c"]
print(my_list)
output
['a, b, c']
Sample 4 (your current scenario):
my_list = []
my_text = '"a", "b", "c"'
my_list.append(my_text) # Single element in the list
print(my_list)
output
['"a, b, c"']

How would I not apply the replace method in a list to a specific item?

Just wondering how I would not have the replace method applied to a specific item in a list (but to the rest). In this example, how I would not apply it to the 3rd item (the 'c' string)?
ls_c = ['a', 'b', 'c', 'd', 'e', 'f']
ls_c_a = (','.join(ls_c))
ls_c_a_1 = ls_c_a.replace(',', '\n')
print('test' + ls_c_a_1)
So the output would look like:
testa
bc
d
e
f
Thanks in advance.
Supposing that the 3rd item will always be "c" string, you could try this:
ls_c_a_1 = ''.join([item if "b" in item else item + "\n" for item in ls_c_a.split(",")])
If this value can be changed, use this:
ls_c_a_1 = [item + "\n" for item in ls_c_a.split(",")]
ls_c_a_2 = ''.join([a[i].replace("\n", "") if i == 1 else a[i] for i in range(len(a))])
You can use a regular expression to find all instances of commas where a c doesn't succeed the comma, using a negative lookahead (?!):
,(?![c])
Then, you can use the Pattern.sub() method to substitute all discovered commas with a newline.
>>> import re
>>> string = ",".join(ls_c)
>>> regex = re.compile(r",(?![c])")
>>> print(regex.sub("\n", string))
a
b,c
d
e
f

Convert a list to a string without 'join'

I'm trying to create my own function that converts a list of characters into a string. I'm not allowed to use 'join'. I need to use a loop to do this. I think I have the basis of it right, but I'm not really sure how to implement it into the function properly. I'm new to programming.
Here's the code I'm using:
def to_string(my_list):
# This line will eventually be removed - used for development purposes only.
print("In function to_string()")
# Display letters in a single line
for i in range(len(my_list)):
print(my_list[i], end='')
# Separate current letter from the next letter
if i<(len(my_list))-1:
print(", ", end='')
# Returns the result
return ('List is:', my_list)
That returns the result I want (if the list is ['a', 'b', 'c'] it returns a, b, c). But there's a 'test file' we're meant to use to run the function which contains this code:
print("\nto_string Test")
string = list_function.to_string(str_list1)
print(string)
print(list_function.to_string(empty))
And it gives this result:
to_string Test
In function to_string()
r, i, n, g, i, n, g('List is:', ['r', 'i', 'n', 'g', 'i', 'n', 'g'])
In function to_string()
('List is:', [])
Which seems to indicate that I messed up entirely, something to do with the 'print' function I think. Can anyone please tell me where I'm going wrong?
Your function prints your string to stdout, then returns the list itself unchanged.
Build a string and return that instead of printing:
def to_string(my_list):
result = ''
last = len(my_list) - 1
for pos, elem in enumerate(my_list):
result += str(elem)
if pos != last:
result += ', '
return result
This loops over all elements, keeping a position counter with the enumerate() function; this way it's easy to detect if we are adding the last element to the result.
You could also use reduce function:
aList=['w','o','r','d']
aString=reduce(lambda x,y:x+y,aList)
If you want to emulate the .join() method of strings than you may want to add a delimiter option to your function.
def to_string(my_list, delimiter):
string = str(my_list.pop(0))
while my_list:
string += delimiter + str(my_list.pop(0))
return string
.pop(n) will delete the nth element from the list and return it.
If you want to return the original list as well:
def to_string(my_list, delimiter):
string = ''
if my_list:
string = my_list[0]
for elem in my_list[1:]:
string += delimiter + str(elem)
return my_list, string
The syntax my_list[n] will get the nth element from the list. Note that the elements are numbered from 0, not from 1. The syntax my_list[n:] will return the elements of the list starting from n. Example:
>>> my_list = ['this', 'is', 'a', 'list']
>>> my_list[1:]
['is', 'a', 'list']
Loop over the list elements and add them to your string. (Just a simpler version of the proposed solutions)
def to_string(my_list):
result_string = ''
for element in my_list:
result_string += element
return result_string
To test:
a_list = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
print to_string(a_list) # prints ringing
b_list = []
print to_string(b_list) # returns empty
Maybe a unique way of doing it.
#Python print() has a unique ability
List = ['a','b','c']
print(*List,sep="")
#### Output ####
abc
# In this method I'm trying to using python's print() ability
# and redirecting the print() from standard output to a temporary variable
# and then using it.
from io import StringIO # Python3
import sys
old_stdout = sys.stdout
result = StringIO() #store everything that is sent to the standard output
sys.stdout = result
print(*List, sep = "") #sends to variable result
#or do any fancy stuff here
sys.stdout = old_stdout # Redirect again the std output to screen
result_string = result.getvalue().strip() # strip() because it has \n at the end
print(result_string,type(result_string),len(result_string),sep="\n")
#this actually prints(), and also the result_string variable has that value
#### Output ####
abc
<class 'str'>
3
This will help you indetail. Store standard output on a variable in Python

python removing whitespace from string in a list

I have a list of lists. I want to remove the leading and trailing spaces from them. The strip() method returns a copy of the string without leading and trailing spaces. Calling that method alone does not make the change. With this implementation, I am getting an 'array index out of bounds error'. It seems to me like there would be "an x" for exactly every list within the list (0-len(networks)-1) and "a y" for every string within those lists (0-len(networks[x]) aka i and j should map exactly to legal, indexes and not go out of bounds?
i = 0
j = 0
for x in networks:
for y in x:
networks[i][j] = y.strip()
j = j + 1
i = i + 1
You're forgetting to reset j to zero after iterating through the first list.
Which is one reason why you usually don't use explicit iteration in Python - let Python handle the iterating for you:
>>> networks = [[" kjhk ", "kjhk "], ["kjhkj ", " jkh"]]
>>> result = [[s.strip() for s in inner] for inner in networks]
>>> result
[['kjhk', 'kjhk'], ['kjhkj', 'jkh']]
You don't need to count i, j yourself, just enumerate, also looks like you do not increment i, as it is out of loop and j is not in inner most loop, that is why you have an error
for x in networks:
for i, y in enumerate(x):
x[i] = y.strip()
Also note you don't need to access networks but accessing 'x' and replacing value would work, as x already points to networks[index]
This generates a new list:
>>> x = ['a', 'b ', ' c ']
>>> map(str.strip, x)
['a', 'b', 'c']
>>>
Edit: No need to import string when you use the built-in type (str) instead.
So you have something like: [['a ', 'b', ' c'], [' d', 'e ']], and you want to generate [['a', 'b',' c'], ['d', 'e']]. You could do:
mylist = [['a ', 'b', ' c'], [' d', 'e ']]
mylist = [[x.strip() for x in y] for y in mylist]
The use of indexes with lists is generally not necessary, and changing a list while iterating though it can have multiple bad side effects.
c=[]
for i in networks:
d=[]
for v in i:
d.append(v.strip())
c.append(d)
A much cleaner version of cleaning list could be implemented using recursion. This will allow you to have a infinite amount of list inside of list all while keeping a very low complexity to your code.
Side note: This also puts in place safety checks to avoid data type issues with strip. This allows your list to contain ints, floats, and much more.
def clean_list(list_item):
if isinstance(list_item, list):
for index in range(len(list_item)):
if isinstance(list_item[index], list):
list_item[index] = clean_list(list_item[index])
if not isinstance(list_item[index], (int, tuple, float, list)):
list_item[index] = list_item[index].strip()
return list_item
Then just call the function with your list. All of the values will be cleaned inside of the list of list.
clean_list(networks)

Categories