convert list into string? [duplicate] - python

This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 2 years ago.
Here is my list ['k:1','d:2','k:3','z:0'] now I want to remove apostrophes from list item and store it in the string form like 'k:1 , d:2, k:3, z:0' Here is my code
nlist = ['k:1','d:2','k:3','z:0']
newlist = []
for x in nlist:
kk = x.strip("'")
newlist.append(kk)
This code still give me the same thing

Just do this : print(', '.join(['k:1','d:2','k:3','z:0']))

if you want to see them without the apostrophes, try to print one of them alone.
try this:
print(nlist[0])
output: k:1
you can see that apostrophes because it's inside a list, when you call the value alone the text comes clean.
I would recommend studying more about strings, it's very fundamental to know how they work.

The parenthesis comes from the way of representing a list, to know wether an element is a string or not, quotes are used
print(['aStr', False, 5]) # ['aStr', False, 5]
To pass from ['k:1','d:2','k:3','z:0'] to k:1 , d:2, k:3, z:0 you need to join the elements.
values = ['k:1','d:2','k:3','z:0']
value = ", ".join(values)
print(value) # k:1, d:2, k:3, z:0

What you have is a list of strings and you want to join them into a single string.
This can be done with ", ".join(['k:1','d:2','k:3','z:0']).

Related

casting string content to list [duplicate]

This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 1 year ago.
Let's assume I have list, and have turned it into a string (to use it as a dictionary key for example). Is there a way to get the list back from the string? This code snippet should illustrate what I want:
list_str = str([1,2,3])
my_list = some_operation(list_str)
such that the variable my_list contains the list [1,2,3]
Any help would be appreciated!
You could use ast.literal_eval(list_str) but the real question is why did you convert it into a string in the first place? You could have converted it to a tuple (immutable and hashable) to use as a dict key
It's not a good idea, but you can try:
# list_str holds your list in a string
vals = list_str[1:-1]
l = [int(x.strip()) for x in vals.split(",")]

Python - change string chars into a list unless recurring [duplicate]

This question already has answers here:
How do I remove duplicates from a list, while preserving order?
(31 answers)
Closed 8 years ago.
I want to print all the characters in a string as a list but for each character to be printed once even if recurring. So far I have:
symbolsx = []
for line in ''.join(word_lines):
for i in line:
symbolsx.append(i)
This prints every character, even if the character is repeated.
symbolsx = list(set(symbolsx))
First pass the list to set function to remove duplicates, then reverted that set back to list by passing it to list function.
How about:
symbolsx = []
for line in ''.join(word_lines):
for i in line:
if i not in symbolsx:
symbolsx.append(i)

Python print list of sets without brackets [duplicate]

This question already has answers here:
Removing set identifier when printing sets in Python
(5 answers)
Closed 9 years ago.
I have a list of sets (using Python).
Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?
Right now I'm getting somthing like this for each item in the list
set(['blah', 'blahh' blahhh')]
And I want it to look more like this
blah,blahh,blahhh
Lots of ways, but the one that occurred to me first is:
s = set([0,1])
", ".join(str(e) for e in s)
Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print. Should work in python 2 and python 3.
For list of sets:
l = [{0,1}, {2,3}]
for s in l:
print(", ".join(str(e) for e in s))
I'm assuming you want a string representation of the elements in your set. In that case, this should work:
s = set([1,2,3])
print " ".join(str(x) for x in s)
However, this is dependent on the elements of s having a __str__ method, so keep that in mind when printing out elements in your set.
Assuming that your list of sets is called set_list, you can use the following code
for s in set_list:
print ', '.join(str(item) for item in s)
If set_list is equal to [{1,2,3}, {4,5,6}], then the output will be
1, 2, 3
4, 5, 6

How to pass a list containing a single string in python? [duplicate]

This question already has an answer here:
Convert list items to tuple
(1 answer)
Closed 9 years ago.
In Python, how do I pass a list that contains only one string?
For example:
def fn(mylist): return len(mylist)
print fn(('abc', 'def')) # prints 2
print fn(('abc')) # prints 3
I want it to print 1 for the one string in the list ('abc') but instead it prints 3 for the 3 characters of the string.
That's a tuple, not a list. To make a one-tuple, do this:
print fn(('abc',))
To make a list of length one, do this:
print fn(['abc'])
In your scenario, I think a list would be more appropriate. Use lists when you have a bunch of the same elements of the same type, and tuples when you have a “record”, or some elements of possibly different types and you don't need to add or remove any entries. (Lists often contain tuples.)
fn(['abc'])
passes a list
fn(('abc'))
passes a string in parentheses which are ignored.
As other posters have pointed out
fn(('abc', ))
passes a tuple.
They are actually called tuples, and you can create a tuple of length one like so:
print fn(('abc',))
when you use ('abc', 'def') it means you are passing a tuple.
A tuple with single element can be declared as ('abc',) .
*note the trailing comma.
passing value as ('xyz') or 'xyz' are same.
So python function len('string') returns the number of character.
also , len(iteratable) gives count of elements in the iteratable.
So, you should use fn(['abc']) or fn(('abc',)) to get the required answer.

How to convert a string list into an integer in python [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
In my python Script I have:
user = nuke.getInput("Frames Turned On")
userLst = [user]
print userLst
Result:
['12,33,223']
I was wondering How I would remove the ' in the list, or somehow convert it into int?
Use split() to split at the commas, use int() to convert to integer:
user_lst = map(int, user.split(","))
There's no ' to remove in the list. When you print a list, since it has no direct string representation, Python shows you its repr—a string that shows its structure. You have a list with one item, the string 12,33,223; that's what [user] does.
You probably want to split the string by commas, like so:
user_list = user_input.split(',')
If you want those to be ints, you can use a list comprehension:
user_list = [int(number) for number in user_input.split(',')]
[int(s) for s in user.split(",")]
I have no idea why you've defined the separate userLst variable, which is a one-element list.
>>> ast.literal_eval('12,33,223')
(12, 33, 223)
>>> result = ['12,33,223']
>>> int(result[0].replace(",", ""))
1233233
>>> [int(i) for i in result[0].split(',')]
[12, 33, 233]
You could use the join method and convert that to an integer:
int(''.join(userLst))
1233223

Categories