I have a list with float values. I want to remove the the brackets from the list.
Floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719]
print (", ".join(Floatlist))
but i am getting an following error :
TypeError: sequence item 0: expected string, float found
but i want to print the list like:
output:14.715258933890,10.215953824,14.8171645397,10.2458542714719
You need to convert the elements to strings.
print (", ".join(map(str, Floatlist)))
or
print (", ".join(str(f) for f in Floatlist)))
.join only operates on iterables that yield strings. It doesn't convert to strings implicitly for you -- You need to do that yourself:
','.join([str(f) for f in FloatList])
','.join(str(f) for f in FloatList) also works (notice the missing square brackets), but on CPython, it's pretty well known that the version with the list comprehension performs slightly better.
You just make a for statement:
for i in Floatlist:
print(i, ', ', end='')
Hope that helps
P.S: This snippet code only works in Python3
Just to print:
print(str(Floatlist).strip('[]'))
#out: 14.71525893389, 10.215953824, 14.8171645397, 10.2458542714719
Related
def remove_char(text):
for letter in text[1]:
text[0] = text[0].replace(letter," ")
return text[0]
This is returning:
'str' object does not support item assignment
Why? And how can I make this work?
In Python, strings are not mutable, which means they cannot be changed. You can, however, replace the whole variable with the new version of the string.
Example:
text = ' ' + text[1:] # replaces first character with space
Strings are immutable. By trying:
text[0] = text[0].replace(letter," ")
you are trying to access the string and change it, which is disallowed due to the string's immutability. Instead, you can use a for loop and some slicing:
for i in range(0, len(y)):
if y[i] == ",":
print y[i+1:len(y)]
break
You can change the string a variable is assigned to (second piece of code) rather than the string itself (your piece of code).
Assuming that the parameter text is a string, the line for letter in text[1]: doesn't make much sense to me since text[1] is a single character. What's the point of iterating over a one-letter string?
However, if text is a list of strings, then your function doesn't throw any exceptions, it simply returns the string that results from replacing in the first string (text[0]) all the letters of the second string (text[1]) by a blank space (" ").
The following examples show how remove_char works when its argument is a list of strings:
In [462]: remove_char(['spam', 'parrot', 'eggs'])
Out[462]: 's m'
In [463]: remove_char(['bar', 'baz', 'foo'])
Out[463]: ' r'
In [464]: remove_char(['CASE', 'sensitive'])
Out[464]: 'CASE'
Perhaps this is not the intended behaviour...
How do I print a list that has numbers and strings to a single string?
For example, I have this list: ["(",3,"+",4,"-",3,")"], I would like it to be printed as :(3+4-4). I tried to use the join command, but I keep having issues with the numbers.
You have to cast the ints to str, str.join expects strings:
l = ["(",3,"+",4,"-",3,")"]
print("".join(map(str,l)))
(3+4-3)
Which is equivalent to:
print("".join([str(x) for x in l]))
To delimit each element with a space use:
print(" ".join(map(str,l)))
Hey I wrote a python code (python 2.7.3) with multiple lists, but when I try to print them they always come with a space. I want to print the list in continuous manner but I'm unable to do so. I have one list which have integer values and other with character.
Eg: list1 (integer list has 123) and list2(character list has ABC).
Desired Output: ABC123
What I'm getting: ABC 123
What I did:
print "".join(list2),int("".join(str(x) for x in list1))
Any suggestion what I'm doing wrong?
l = ["A","B","C"]
l2 = [1,2,3]
print "".join(l+map(str,l2))
ABC123
map casts all ints to str, it is the same as doing [str(x) for x in l2].
The space comes from the print statement. It automatically inserts a space between items separated with comma. I suppose you don't need to covert the concatenated string into an integer, then you concatenate strings from join and print them as one.
print "".join(list2)+"".join(str(x) for x in list1)
Alternatively you can switch to python3's print function, and use its sep variable.
from __future__ import print_function
letters=['A','B','C']
nums=[1,2,3]
print("".join(letters),int("".join(str(x) for x in nums)), sep="")
Try concatenating the two lists you want while printing. Use "+" instead of ",".
Here 'int' will give error as you can concatenate only strings. So try,
print "".join(list2)"".join(str(x) for x in list1)
The , is what's adding the space since you are printing two things, a string 'ABC' and an integer 123. Try using +, which directly adds two strings together so you can print the string 'ABC123'
>>> list1=[1,2,3]
>>> list2=['A','B','C']
>>> print "".join(list2),int("".join(str(x) for x in list1))
ABC 123
>>> print "".join(list2)+"".join(str(x) for x in list1)
ABC123
print adds a single space automatically between commas.
You can use the new print function:
from __future__ import print_function
print("".join(list2),int("".join(str(x) for x in list1)), sep="")
See docs.
Note: This function is not normally available as a built-in since the
name print is recognized as the print statement. To disable the
statement and use the print() function, use this future statement at
the top of your module
This is similar to what I want to do: breaking a 32-bit number into individual fields
This is my typical "string" 00000000110000000000011000000000
I need to break it up into four equal parts:
00000000
11000000
00000110
00000000
I need to append the list to a new text file with the original string as a header.
I know how to split the string if there were separators such as spaces but my string is continuous.
These could be thought of as 32bit and 8bit binary numbers but they are just text in a text file (for now)!
I am brand new to programing in Python so please, I need patient details, no generalizations.
Do not assume I know anything.
Thank you,
Ralph
This should do what you want. See comprehensions for more details.
>>> s = "00000000110000000000011000000000"
>>> [s[i:i+8] for i in xrange(0, len(s), 8)]
['00000000', '11000000', '00000110', '00000000']
+1 for Robert's answer. As for 'I need to append the list to a new text file with the original string as a header':
s = "00000000110000000000011000000000"
s += '\n' + '\n'.join(s[i:i+8] for i in xrange(0, len(s), 8))
will give
'00000000110000000000011000000000\n00000000\n11000000\n00000110\n00000000'
thus putting each 'byte' on a separate line as I understood from your question...
Edit: some notes to help you understand:
A list [] (see here) contains your data, in this case, strings, between its brackets. The first item in a list is retrieved as in:
mylist[0]
in Python, a string is itself also an object, with specific methods that you can call. So '\n' (representing a carriage return) is an object of type 'string', and you can call it's method join() with your list as argument:
'\n'.join(mylist)
The elements in the list are then 'joined' together with the string '\n' in between each element. The result is no longer a list, but a string. Two strings can be added together, thus
s += '\n' + '\n'.join(mylist)
adds to s (which was already a string), the right part which is itself a 'sum' of strings.
(I hope that clears some things up?)
For reference, here are a few alternatives for splitting strings into equal length parts:
>>> import re
>>> re.findall(r'.{1,8}', s, re.S)
['00000000', '11000000', '00000110', '00000000']
>>> map(''.join, zip(*[iter(s)]*8))
['00000000', '11000000', '00000110', '00000000']
The zip method for splitting a sequence into n-length groups is documented here, but it will only work for strings whose length is evenly divisible by n (which won't be an issue for this particular question). If the string length is not evenly divisible by n you could use itertools.izip_longest(*[iter(s)]*8, fillvalue='').
Strings, Lists and Touples can be broken using the indexing operator [].
Using the : operator inside of the indexing operator you can achieve fields there.
Try something like:
x = "00000000110000000000011000000000"
part1, part2, part3, part4 = x[:8], x[8:16], x[16:24], x[24:]
you need a substring
x = 01234567
x0 = x[0:2]
x1 = x[2:4]
x2 = x[4:6]
x3 = x[6:8]
So, x0 will hold '01', x1 will hold '23', etc.
I am comparing 2 txt files that are ls -R of the etc directory in a linux system. I compared the 2 files using difflib.differ and got this list as my result (i put the dots to keep the list short in here):
result = [' etc:\n', ' ArchiveSEL\n', ' HOSTNAME\n', ' RMCPUser\n', ...,
' qcleaner\n', '+ extraFile\n', ' rc.d\n', '+ extraFile2\n', ...,
' resolv.conf\n', ' wu-ftpd\n']
I want to be able to take the strings with the '+' sign out to do something else. how do i manipulate the list? in the example above, i want to be able to get this string "extraFile" and "extraFile2".
Thanks to all the people who posted solutions. It helps a lot and I am grateful :)
Here's what I did to get the string I wanted:
newresult = [file[2:-1] for file in result if file.startswith('+')]
to print out the strings:
for i in range (len(newresult)):
print newresult[i]
THANKS~!!! :)
You can use list comprehension:
newlist = [file[1:] for file in result if file.startswith('+')]
# ^-- gets rid of `+` at the beginning
See the string methods documentation.
And if you want to get rid of the newline character and whitespaces just do:
newlist = [file[1:].strip() for file in result if file.startswith('+')]
Another way would be to use filter(), but you cannot manipulate the string then (just want to mention it for completeness):
newlist = filter(lambda s: s.startswith('+'), result)
>>> [x.strip('+').strip() for x in result if x.startswith("+")]
['extraFile', 'extraFile2']
Improved version with stripping out '+' and whitespace/linebreaks
Try a list comprehension : [x for x in result if x[0]=='+']