I've written a function in python that returns a list, for example
[(1,1),(2,2),(3,3)]
But i want the output as a string so i can replace the comma with another char so the output would be
'1#1' '2#2' '3#3'
Any easy way around this?:)
Thanks for any tips in advance
This looks like a list of tuples, where each tuple has two elements.
' '.join(['%d#%d' % (t[0],t[1]) for t in l])
Which can of course be simplified to:
' '.join(['%d#%d' % t for t in l])
Or even:
' '.join(map(lambda t: '%d#%d' % t, l))
Where l is your original list. This generates 'number#number' pairs for each tuple in the list. These pairs are then joined with spaces (' ').
The join syntax looked a little weird to me when I first started woking with Python, but the documentation was a huge help.
You could convert the tuples to strings by using the % operator with a list comprehension or generator expression, e.g.
ll = [(1,1), (2,2), (3,3)]
['%d#%d' % aa for aa in ll]
This would return a list of strings like:
['1#1', '2#2', '3#3']
You can concatenate the resulting list of strings together for output. This article describes half a dozen different approaches with benchmarks and analysis of their relative merits.
' '.join([str(a)+"#"+str(b) for (a,b) in [(1,1),(2,2),(3,3)]])
or for arbitrary tuples in the list,
' '.join(['#'.join([str(v) for v in k]) for k in [(1,1),(2,2),(3,3)]])
In [1]: ' '.join('%d#%d' % (el[0], el[1]) for el in [(1,1),(2,2),(3,3)])
Out[1]: '1#1 2#2 3#3'
[ str(e[0]) + ',' + str(e[1]) for e in [(1,1), (2,2), (3,3)] ]
This is if you want them in a collection of string, I didn't understand it if you want a single output string or a collection.
[str(item).replace(',','#') for item in [(1,1),(2,2),(3,3)]]
You only need join and str in a generator comprehension.
>>> ['#'.join(str(i) for i in t) for t in l]
['1#1', '2#2', '3#3']
>>> ' '.join('#'.join(str(i) for i in t) for t in l)
'1#1 2#2 3#3'
you could use the repr function and then just replace bits of the string:
>>> original = [(1,1),(2,2),(3,3)]
>>> intermediate = repr(original)
>>> print intermediate
[(1, 1), (2, 2), (3, 3)]
>>> final = intermediate.replace('), (', ' ').replace('[(','').replace(')]','').replace(', ','#')
>>> print final
1#1 2#2 3#3
but this will only work if you know for certain that none of tuples have the following character sequences which need to be preserved in the final result: ), (, [(, )], ,
Related
I have a list of strings in this format:
['5,6,7', '8,9,10']
I would like to convert this into the format:
[(5,6,7), (8,9,10)]
So far I have tried this:
[tuple(i.split(',')) for i in k]
And I obtain:
[('5','6','7'), ('8','9','10')]
I am a bit stuck on how to simply convert the strings into tuples of integers. Thank you
If your strings are strings representation of number, then:
[tuple(int(s) for s in i.split(',')) for i in k]
The following solution is for me the most readable, perhaps it is for others too:
a = ['5,6,7', '8,9,10'] # Original list
b = [eval(elem) for elem in a] # Desired list
print(b)
Returns:
[(5, 6, 7), (8, 9, 10)]
The key point here being the builtin eval() function, which turns each string into a tuple.
Note though, that this only works if the strings contain numbers, but will fail if given letters as input:
eval('dog')
NameError: name 'dog' is not defined
Your question requires the grouping of elements. Hence, an appropriate solution would be:
l = ['5','6','7', '8','9','10']
[(lambda x: tuple(int(e) for e in x))((i,j,k)) for (i, j, k) in zip(l[0::3], l[1::3], l[2::3])]
This outputs:
[(5, 6, 7), (8, 9, 10)]
As desired.
listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use split
res = [tuple(map(int, sub.split(', '))) for sub in listA]
# Result
print("List of tuples: \n",res)
source: https://homiedevs.com/example/python-convert-list-of-strings-to-list-of-tuples#64288
I have a 2-element list like:
[(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
I want to get the first words of tuples that is I want to get a 2-element list as:
["sugar","father"]
I don't know how can I achive this since I am unfamilier with u' notation. Can anyone help or give some hints?
Using str methods
Ex:
d = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
print([i[1].split("+")[0].split("*")[1].replace('"', "").strip() for i in d])
Output:
[u'sugar', u'father']
str.split to split string by ("+" and "*")
str.replace to replace extra quotes
str.strip to remove all trailing or leading space.
You can find the value of an index location using square brackets.
myList[index]
In nested lists:
myList[indexInOuterList][indexInInnerList]
For your situation:
myList[indexInList][indexInTuple]
mylist = [(2, u'0.267*"sugar" + 0.266*"bad"'), (0, u'0.222*"father" + 0.222*"likes"')]
myList[0][0] #This is the integer 2
So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]
I have a list of strings in this format:
['5,6,7', '8,9,10']
I would like to convert this into the format:
[(5,6,7), (8,9,10)]
So far I have tried this:
[tuple(i.split(',')) for i in k]
And I obtain:
[('5','6','7'), ('8','9','10')]
I am a bit stuck on how to simply convert the strings into tuples of integers. Thank you
If your strings are strings representation of number, then:
[tuple(int(s) for s in i.split(',')) for i in k]
The following solution is for me the most readable, perhaps it is for others too:
a = ['5,6,7', '8,9,10'] # Original list
b = [eval(elem) for elem in a] # Desired list
print(b)
Returns:
[(5, 6, 7), (8, 9, 10)]
The key point here being the builtin eval() function, which turns each string into a tuple.
Note though, that this only works if the strings contain numbers, but will fail if given letters as input:
eval('dog')
NameError: name 'dog' is not defined
Your question requires the grouping of elements. Hence, an appropriate solution would be:
l = ['5','6','7', '8','9','10']
[(lambda x: tuple(int(e) for e in x))((i,j,k)) for (i, j, k) in zip(l[0::3], l[1::3], l[2::3])]
This outputs:
[(5, 6, 7), (8, 9, 10)]
As desired.
listA = ['21, 3', '13, 4', '15, 7']
# Given list
print("Given list : \n", listA)
# Use split
res = [tuple(map(int, sub.split(', '))) for sub in listA]
# Result
print("List of tuples: \n",res)
source: https://homiedevs.com/example/python-convert-list-of-strings-to-list-of-tuples#64288
So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]