Convert list to string using python - python

I have the list it contain int ,float and string:
lists = [10, "test", 10.5]
How Can i convert above list to string? I have tried:
val = ','.join(lists)
print val
I am getting error like this:
sequence item 0: expected string, int found
How can I solve this issue?

Firstly convert integers to string using strusing map function then use join function-
>>> ','.join(map(str,[10,"test",10.5]) )#since added comma inside the single quote output will be comma(,) separated
>>> '10,test,10.5'
Or if you want to convert each element of list into string then try-
>>> map(str,[10,"test",10.5])
>>> ['10', 'test', '10.5']
Or use itertools for memory efficiency(large data)
>>>from itertools import imap
>>>[i for i in imap(str,[10,"test",10.5])]
>>>['10', 'test', '10.5']
Or simply use list comprehension
>>>my_list=['10', 'test', 10.5]
>>>my_string_list=[str(i) for i in my_list]
>>>my_string_list
>>>['10', 'test', '10.5']

The easiest way is to send the whole thing to str() or repr():
>>> lists = [10, "test", 10.5]
>>> str(lists)
"[10, 'test', 10.5]"
repr() may produce a different result from str() depending on what's defined for each type of object in the list. The point of repr() is that you can send such strings back to eval() or ast.literal_eval() to get the original object back:
>>> import ast
>>> lists = [10, "test", 10.5]
>>> ast.literal_eval(repr(lists))
[10, 'test', 10.5]

a = ['b','c','d']
strng = ''
for i in a:
strng +=str(i)
print strng

The error you are getting because join wants elements to be string type, but in your list there is integer too, so 1st you have to convert them to type string.
you can use list comprehension and str and join to join them
>>> lists = [10,"test",10.5]
>>> ",".join(str(x) for x in lists)

You have to pass each item in your list as a string into the ','.join(sequence). Consider using:
val = ','.join([str(item) for item in lists])
print val

If you want to convert each element in the list to a string, you could do it simply using a for-loop.
for i in range(len(lists)):
lists[i] = str(lists[i])
Alternatively, if you want to make one string where all elements are joined together, you could edit the code above slightly.
string_of_lists = ""
for i in lists:
string_of_lists += str(i)
As you can tell, this is another way of doing it, apart from the other solutions using join.
I hope I helped!

This is also possible. Here x variable is list.
>>> '%s'*len(x) % tuple(x)

As mentioned here
list=['a/b/c', 'd/e/f']
file_list_string= ' '.join(list)
file_list_string= ' '.join(str(file) for file in list)

import functools
lists = [10,"test",10.5]
print(functools.reduce(lambda x,y:x+","+y,list(map(str,lists))))

You could always do it the dirty way:
list_name = ["a", "b", "c"];
string_name = "";
for c in list_name:
string_name += c
print(string_name)
OUTPUT:
"abc"
That should work with ints, floats, and strings, always converting them to string type.

Related

String conversion returns null

Trying to convert this string (put in the variable a1):
'\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
to:
'\'start\':\'redis_import\',\'dim_user_level\':\'redis_import\''
I have tried print a1.split(',').reverse() but this returns null. Why? and how to achieve this without using a loop?
Any help is appreciated.
If you want it as a dict.
s = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
res = {}
for i in s.split(","):
val = list(reversed(i.split(":")))
res[val[0].replace("'", "")] = val[1].replace("'", "")
print(res)
Output:
{'start': 'redis_import', 'dim_user_level': 'redis_import'}
First of all .reverse() method reverse the list and returns None
so you can use reversed() which will return you iterator of reverse of the list
a = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
print(', '.join([':'.join(reversed(i.split(':'))) for i in a.split(',')])) # "'start':'redis_import', 'dim_user_level':'redis_import'"
Split on comma, split on colons, reverse, join colons, join commas:
s = '\'redis_import\':\'start\',\'redis_import\':\'dim_user_level\''
','.join(':'.join(i.split(':')[::-1]) for i in s.split(','))
#"'start':'redis_import','dim_user_level':'redis_import'"
To understand this better just observe the output of these different calls:
>>> s.split(',')
["'redis_import':'start'", "'redis_import':'dim_user_level'"]
>>> s.split(',')[0]
"'redis_import':'start'"
>>> s.split(',')[0].split(':')
["'redis_import'", "'start'"]
>>> s.split(',')[0].split(':')[::-1]
["'start'", "'redis_import'"]
>>> ','.join(('a', 'b', 'c'))
'a,b,c'
>>> [i[::-1] for i in [[1,2], [3,4]]]
[[2, 1], [4, 3]]
Some further reading:
str.split - the method used to separate the strings at delimiters
str.join - the method used to join iterables back to strings
a good introduction to those one-line generator expressions
a section about slicing and how they can be used to reverse sequences

Parsing,splicing and structuring nested strings to list in Python

I can't imagine I'm going to get much help from this due to my inability to explain it. But for instance I have a string like so:
s = "[1,[2,2,[3,4]],5]"
and I need to convert it into a nested list item as such
lst = ["1",["2","2",["3","4"]],"5"]
that if I were to go lst[1][2][0] it would return '3'.
The way I have tried to do it was by creating a substring for every number within '[' and end of string characters and then slowly nest it back up
def ParseList(strlist):
if '[' in strlist:
print strlist
return ParseList(GetBetweenChar(strlist,'[',None))
else:
return strlist
however it returns:(which although maybe a good start? I dont know where to continue)
[1,[2,2,[3,4]],5]
1,[2,2,[3,4]],5
2,2,[3,4]],
3,4]]
which I would think I would append that to a list item but I dont know how to..
You can use ast.literal_eval to safely convert the string to a nested list of integers. Then define a nested map function to convert to all elements to strings, whilst maintaining the nesting structure.
from ast import literal_eval
s = "[1,[2,2,[3,4]],5]"
ls = literal_eval(s)
# yes I know there is something else called nmap
def nmap(fn, iterable):
res = []
for i in iterable:
if isinstance(i, list): # could be tuple or something else?
res.append(nmap(fn, i))
else:
res.append(fn(i))
return res
result = nmap(str, ls)
print(result)
print(result[1][2][0])
result:
['1', ['2', '2', ['3', '4']], '5']
3
You can use eval(). Just be careful to make sure the string is safe because eval will convert a string to valid python code.
>>> eval("[1,[2,2,[3,4]],5]")[1][2][0]
3
Some more info: What does Python's eval() do?
If you didn't require every piece to be a string, but you could let numbers be numbers, then you can use the json library:
>>> s = "[1,[2,2,[3,4]],5]"
>>> import json
>>> json.loads(s)
[1, [2, 2, [3, 4]], 5]
Notice that if your original list contains numbers or booleans, they will stay as numbers or booleans. This is probably what you want, BUT if you really need everything to be strings, then you can recurse through the nested arrays and apply str to everything (look for "How to do flatmap in Python") or request further help in the comment section below.
You could proceed by first adding the quotes around the digits, then eval the list:
s = "[1,[2,2,[3,4]],5]"
res = ''
for c in s:
if c.isdigit():
res += '"' + c + '"'
else:
res += c
s = eval(res)
s
output:
['1', ['2', '2', ['3', '4']], '5']
This will work for single digit numbers; a little bit more work would be needed for multiple digits, or floats
Eval is not safe for user input.
You can do something like for python (2.6+):
>>> import ast
>>> s = "[1,[2,2,[3,4]],5]"
>>> lst = ast.literal_eval(s)
>>> str(lst[1][2][0])
'3'

Writing a nested loop in python [duplicate]

This question already has answers here:
how to change [1,2,3,4] to '1234' using python
(2 answers)
Closed 7 years ago.
I'm a Python beginner struggling to write code that uses the list myList = [['A','B','C'],[4,5,​6],[7,8,9]] and generates the output below:
Input:
myList = [['A','B','C'],[4,5,​6],[7,8,9]]
Expected output: (by line)
-A-B-C-
-4-5-6-
-7-8-9-
I've tried a few different things but am not sure how to approach the confluence of strings and integers in the same list.
I can get:
>>> for i in range (0,myList_len):
... print ("-".join(myList[i]))
...
A-B-C
But I can't get this to work for the numbers. Any help would be much appreciated!
You could use map to convert from int to str
for l1 in myList:
print '-' + '-'.join(map(str, l1)) + '-'
When you try to join numbers, you get the following error:
TypeError: sequence item 0: expected str instance, int found
This is because str.join() only works with str items in the iterable, but you pass it int objects instead.
So in order to properly join them, you need to convert them to strings first. You can either do that by calling str on every item using map, or by using a list comprehension:
>>> lst = [4, 5, 6]
>>> '-'.join(map(str, lst))
'4-5-6'
>>> '-'.join([str(x) for x in lst])
'4-5-6'
The "join" operator expects a list of strings, so you have to turn your numbers to strings first, using the "str" operator that turns anything into a string.
for l in myList:
print '-' + '-'.join([str(x) for x in l]) + '-'
join works on strings, not numbers. You need to convert:
print ("-".join(str(num) for num in myList[i]))
Now, just add the hyphens at start and finish, and you're done.
Try the following:
for sublist in myList:
print("-".join(map(str, sublist)))
The output is:
A-B-C
4-5-6
7-8-9
If you want leading and trailing hyphens as well, use:
for sublist in myList:
print("-" + "-".join(map(str, sublist)) + "-")
The output is:
-A-B-C-
-4-5-6-
-7-8-9-
The for loop iterates over the sublists. The map(str, sublist) call applies str to each element of the sublist, converting it to a string. Without this, your non-string entries (i.e., numbers) were causing errors when passed to join.

How can i separate a string that is in a list into 2 parts?

I currently have a list that looks like the following:
list = ['325 153\n', '509 387\n', '419 397\n']
I am wondering how could i access these strings individually so i could use it in a function such as
for (x, y) in list:
where x is the first number of the string and y is the second number (separated by the space)
Is a good way to do this to turn the string into tuples somehow? I have tried using the 'split' function as i believe it is not valid for a list.
>>> a_list = ['325 153\n', '509 387\n', '419 397\n']
>>> [ i.split() for i in a_list ]
[['325', '153'], ['509', '387'], ['419', '397']]
You can iterate one the elements of the list:
for elem in list:
a, b = elem.split()[0], elem.split()[1]
a and b will be the elements and you can process them just as you wish.
[tuple(x.split()) for x in list]
this will return you a list of tuples
There is the split() method for string. Before using it you should use strip() to get rid of the training \n. At the end you can put both into a list comprehension:
for x, y in [item.strip().split(" ", 1) for item in lst]:
Note that I replace list with lst. list is a built-in type and should not be used as variable name.

Python convertion of list of strings to list of tuples

How to convert following list
['abc,cde,eg,ba', 'abc,cde,ba']
in to list of tuples?
[('abc','cde','eg','ba'), ('abc','cde','ba')]
What I have tried
output = []
for item in my_list:
a = "','".join((item.split(',')))
output.append(a)
In your loop, you are splitting the string (which will give you a list), but then you are joining it back with a ,, which is returning to you the same string:
>>> 'a,b'.split(',')
['a', 'b']
>>> ','.join('a,b'.split(','))
'a,b'
You can convert a list to a tuple by passing it to the the built-in tuple() method.
Combining the above with a list comprehension (which is an expression that evaluates to a list), gives you what you need:
>>> [tuple(i.split(',')) for i in ['abc,cde,eg,ba', 'abc,cde,ba']]
[('abc', 'cde', 'eg', 'ba'), ('abc', 'cde', 'ba')]
The longhand way of writing that is:
result = []
for i in ['abc,cde,eg,ba', 'abc,cde,ba']:
result.append(tuple(i.split(',')))
print(result)
t=['abc,cde,eg,ba', 'abc,cde,ba']
for i in t:
print tuple(i.split(','))
you can split the 2 elements. Here is my code
['abc,cde,eg,ba', 'abc,cde,ba']
a='abc,cde,eg,ba'
b='abc,cde,ba'
c=[]
c.append(tuple(a.split(',')))
c.append(tuple(b.split(',')))
print c

Categories

Resources