Converting a set to a string - python

So I'm supposed to create a function that takes any sort of iterable input and converts it into a string of that input separated by spaces. For example, if you were to call iteration_to_string("abcd") it would return "a b c d " (the space at the end is allowed). or if [1, 2, 3, 4] is the input, it should return "1 2 3 4 ". All I have so far is how to turn the input into a set and Im confused where to go to turn it into a string. I assume it would be adding something into the for loop that would somehow concatenate the inputs together with a space but Im not sure how to do that. Any help is appreciated!
def iteration_to_string (data):
new = set()
for i in range (len(data)):
new.add(data[i])
return " ".join(new)

your code might not work for list containing element int like [1,2,3,4] because join takes string
so you can convert them to int before join like this:
>>> def my_join(x):
... return " ".join(map(str, x))
...
>>> my_join([1, 2, 3, 4])
'1 2 3 4'
you can use list comprehension, if you dont want to use map
>>> def my_join(x):
... return " ".join(str(element) for element in x))
>>> my_join(['a', 'b' ,'c', 'd'])
'a b c d'

for any iterable
' '.join(iterable)
will return a string with all the elements in iterable separated by a space. refer to str.join(iterable).
if the elements in iterable are not strings you need to
' '.join(str(item) for item in iterable)
(you can do this with any other string as well; ''.join(iterable) if you do not want any spaces in between).

Related

Select non empty elements of list in Python [duplicate]

This question already has answers here:
Joining multiple strings if they are not empty in Python
(3 answers)
Closed 5 years ago.
Given:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
list = (a, b, c, d, e)
How can I get a string using all the non empty elements of the list ?
Desired output:
'aaa,ccc,eee'
Using a generator expression:
",".join(string for string in lst if len(string) > 0)
The ",".join() part is using the join() method of strings, which takes an iterable argument and outputs a new string that concatenates the items using "," as delimiter.
The generator expression between parenthesis is being used to filter empty strings out of the list.
The original list doesn't change.
The shortest thing you can do is
','.join(filter(None, mytuple))
(I renamed list to mytuple in oder to not shadow the builtin list.)
You can use a generator-expression:
','.join(s for s in list if s)
which outputs:
'aaa,ccc,eee'
Why?
This takes advantage of the fact that an empty string evaluates to False.
This can be seen clearer through some examples:
>>> if "a":
... print("yes")
...
yes
>>> if " ":
... print("yes")
...
yes
>>> if "":
... print("yes")
...
>>>
So the generator says: for each string in list, keep 'if string' - i.e. if the string is not empty.
We then finally use the str.join method that will take each string in the iterator that is passed into it (here a generator) and concatenate them together with whatever the str is. So here we use a ',' as the string to get the desired result.
A little example of this:
>>> ','.join(['abc', 'def', 'ghi'])
'abc,def,ghi'
**As a side note, you shouldn't name your variable list as it overrides the built-in list() function:
>>> list((1, 2, 3))
[1, 2, 3]
>>> list = 1
>>> list((1, 2, 3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
You can try this one too:
a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'
tup = (a, b, c, d, e)
res = ",".join(filter(lambda i: not i=='', tup))
print(res)
The output will be:
aaa,ccc,eee
It is also a good practice not to use list as a variable name, as it is a reserved keyword from Python.

print comma separated if more than two values in the list python

My input1:
values = ['1','2']
Expected output to print
print 1, 2
my input2:
values = ['1']
Expected output to print
print 1
my input3:
values = ['1','2','3']
Expected output to print
print 1,2,3
Below is what i tried:
for x in values:
print x
Just call join passing in your list and if it is only one element, it won't add the "comma":
print(','.join(['1']))
output:
1
print(','.join(['1', '2']))
output:
1,2
print(','.join(['1', '2', '3']))
output:
1,2,3
If you have a list of integers, or a mix of strings and integers, then you would have to call str on the integer parts in your list. However, the easiest way to go about doing this would be to either call map on your list (map will apply a callable to each item in your list) to cast to the appropriate str, or perform a generator comprehension to cast to int:
comprehension:
print(",".join(str(i) for i in [1,2,3]))
map:
print(",".join(map(str, [1,2,3])))
Just simple as:
print(','.join(myList))
What you type in the command for print isn't exactly what comes out. Basically the commas in the print command just separate out each item you asked it to print but don't tell it to print commas itself. i.e.
>>> print 1, 2, 3
1 2 3
The key is to create the text or string how you want it to look and then print that.
>>> text = ','.join(str(x) for x in [1, 2, 3])
>>> print text
1,2,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.

Command Line Python Comma Separated User Input int Values

math.pow (base/exponent) requires comma separated values...working fine for pre-assigned values, but having trouble with user-submitted values (experimenting in command line). Help appreciated as I want to develop this kind of thing eventually making a basic math test.
exp = int(raw_input())
while exp:
print math.pow(int(raw_input))
The errors I'm getting are
ValueError: invalid literal for int() with base 10: '2,3' (which seems weird as this is an exponent, not log function...)
When I try:
exp = (raw_input())
while exp:
print math.pow(exp)
I get error:
pow expected 2 arguments, got 1
Even though I'm submitting 2,3 for example (with comma).
I also tried concatenating the input with .split, but got error regarding pow requiring integers, not "list."
When you enter an input with a comma, you get a tuple. You can either use
eval(raw_input())
Or just
input()
To get this from a string to a usable format. Once you have a tuple, you can use * notation to "unpack" the tuple. So instead of calling math.pow((2, 3)), where the one argument is the tuple (2, 3), you will be calling math.pow(2, 3).
>>> exp = input()
2, 3
>>> math.pow(*exp)
8.0
"2,3" is a string, passing this to a function won't make it act like two different parameters separated by ,(as you expected).
>>> def func(arg):
... print arg
...
>>> func('a, b')
a, b # arg is a variable that stores the passed string
You should convert that string into two numbers first by splitting it at comma first and then applying int() to each if it's item.
>>> import math
>>> math.pow(*map(int, '2,3'.split(',')))
8.0
First split the string at ',' using str.split:
>>> '2,3'.split(',')
['2', '3'] #str.split returns a list
Now as we need integers so apply int() to each value:
>>> map(int, '2,3'.split(',')) #apply int() to each item of the list ['2', '3']
[2, 3]
Now as pow expects two arguments so you can use * notation to unpack this list and pass
the items to math.pow.
>>> math.pow(*[2 , 3])
8.0
A even simpler way would be to use sequence unpacking:
>>> a, b = [2, 3]
>>> math.pow(a, b)
8.0
There's another tool in python library that can convert comma separated items in a string into a tuple:
>>> from ast import literal_eval
>>> literal_eval('1, 2')
(1, 2)
>>> a,b  = literal_eval('1, 2')
>>> a
1
>>> b
2

Get the first character of the first string in a list?

How would I get the first character from the first string in a list in Python?
It seems that I could use mylist[0][1:] but that does not give me the first character.
>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'
You almost had it right. The simplest way is
mylist[0][0] # get the first character from the first item in the list
but
mylist[0][:1] # get up to the first character in the first item in the list
would also work.
You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.
Get the first character of a bare python string:
>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll
Get the first character from a string in the first position of a python list:
>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'
Numpy operations are very different than python list operations.
Python has list slicing, indexing and subsetting. Numpy has masking, slicing, subsetting, indexing.
These two videos cleared things up for me.
"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015:
https://youtu.be/EEUXKG97YRw?t=22m22s
"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc:
https://youtu.be/gtejJ3RCddE?t=1h24m54s
Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.
If you have the following structure:
mylist = ['base', 'sample', 'test']
And want to get fist char for the first one string(item):
myList[0][0]
>>> b
If all first chars:
[x[0] for x in myList]
>>> ['b', 's', 't']
If you have a text:
text = 'base sample test'
text.split()[0][0]
>>> b
Try mylist[0][0]. This should return the first character.
If your list includes non-strings, e.g. mylist = [0, [1, 's'], 'string'], then the answers on here would not necessarily work. In that case, using next() to find the first string by checking for them via isinstance() would do the trick.
next(e for e in mylist if isinstance(e, str))[:1]
Note that ''[:1] returns '' while ''[0] spits IndexError, so depending on the use case, either could be useful.
The above results in StopIteration if there are no strings in mylist. In that case, one possible implementation is to set the default value to None and take the first character only if a string was found.
first = next((e for e in mylist if isinstance(e, str)), None)
first_char = first[0] if first else None

Categories

Resources