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
Related
I have strings of characters in different languages, mainly Japanese, and they show up fine when I try to print them as strings. However, when I add many of them to a python list, and then print out the list, they display as text like this: xe9
for example:
string1 = "西野カナ- NO. 1"
string2 = "첫눈처럼 너에게 가겠다"
list1 = []
list1.append(string1)
list1.append(string2)
print list1
for item in list1:
print item
These two prints will give me different outputs:
['\xe8\xa5\xbf\xe9\x87\x8e\xe3\x82\xab\xe3\x83\x8a- NO. 1 NEW', '\xec\xb2\xab\xeb\x88\x88\xec\xb2\x98\xeb\x9f\xbc \xeb\x84\x88\xec\x97\x90\xea\xb2\x8c \xea\xb0\x80\xea\xb2\xa0\xeb\x8b\xa4']
西野カナ- NO. 1 NEW
첫눈처럼 너에게 가겠다
How would I get the list to print the actual characters too?
Actually,when you print a list or write to a file, it internally calls the str() method,and list internally calls repr() on its elements. So you are seeing is repr() returns.
print repr(string1)
'\xe8\xa5\xbf\xe9\x87\x8e\xe3\x82\xab\xe3\x83\x8a- NO. 1'
It is really discouraged.So if you want to avoid encoding problem, you should start to think seriously about switching to Python3.
You can check out this or see unicode in python2 and python3
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
I wrote a program in which the user may enter any string. It should:
Delete all the vowels.
Insert the character "." before each consonant.
Replaces all uppercase consonants with corresponding lowercase ones.
Here is the code I wrote:
s=raw_input()
k=s.lower()
listaa=[]
for x in k:
listaa.append(x)
if x=='a':
listaa.remove('a')
if x=='o':
listaa.remove('o')
if x=='y':
listaa.remove('y')
if x=='e':
listaa.remove('e')
if x=='u':
listaa.remove('u')
if x=='i':
listaa.remove('i')
for a in listaa:
print '.%s'%(a),
This code works fine, but for example if I use the input tour, the output is .t .r. Although this is right, it's not exactly what i want. I want to remove spaces between them. I want output that looks like: .t.r
How do I do this?
If you put a comma after a print, it adds a space to the print statement. To not print a space or newline, use sys.stdout.write()
Fixed code:
import sys
s=raw_input()
k=s.lower()
listaa=[]
for x in k:
listaa.append(x)
if x=='a':
listaa.remove('a')
if x=='o':
listaa.remove('o')
if x=='y':
listaa.remove('y')
if x=='e':
listaa.remove('e')
if x=='u':
listaa.remove('u')
if x=='i':
listaa.remove('i')
for a in listaa:
sys.stdout.write('.%s' % a)
Note: you will need to add the import sys statement to use sys.stdout.write
Avoid using remove, since it removes the first occurrence of an item.
Instead, determine what you need to append before appending:
if x in 'bcdfghjklmnpqrstvwxyz':
listaa.append('.')
listaa.append(x)
elif x not in 'aeiou':
# If x is neither a vowel nor a consonant, it is appended.
listaa.append(x)
Also, it would be good to convert your list back to a string at the end:
result = ''.join(listaa)
print result
Regular expressions (contained in the re library) are designed to do exactly this sort of stuff.
import re
import string
alphabet = string.ascii_lowercase
vowels = 'aeiou'
consonants = "".join(set(alphabet)-(set(vowels)))
vowelre = re.compile("["+vowels+"]", re.IGNORECASE)
consonantre = re.compile("(["+consonants+"]){1}", re.IGNORECASE)
text = "Mary had a little lamb The butcher killed it DEAD"
print(vowelre.sub("", text))
print(consonantre.sub(".", text))
I note that you've put the Python 2.7 tag on your query. If you are using 2.7 then I would recommend you get used to using the Python 3 style print function. To enable this you may need a line
from __future__ import print_function
in your code.
tim#merlin:~$ python retest.py
Mry hd lttl lmb Th btchr klld t DD
.a.. .a. a .i...e .a.. ..e .u...e. .i..e. i. .EA.
HTH
using print elem, in python uses the delimiter of a space which means it automatically prints a space after each call to print. this can be avoided by calling print only once by making a single string:
print ''.join(listaa)
str.join(list) is a built in string method that joins a list's elements together with str. the problem with this is that it wont have a period before each consonant.
your logic can also be changed to remove if statements. best way to do this is to change your logic to a add if not in kind of way:
s=raw_input()
k=s.lower()
listaa=[]
for x in k:
if x not in ['a','e','i','o','u']: listaa.append('.'+x.lower())
all this does is check if x is a vowel, if not add a string made up of a period and x
you can also do this all in one line:
print ''.join('.'+x.lower() for x in raw_input() if x not in 'aeiou')
Code so far:
fullname = "John Doe"
namelist = fullname.split()
for word in namelist:
print word[:2].lower(),
This outputs:
jo do
I want it to output:
jodo
Any and all suggestions welcomed :)
The comma creates a space. Try creating a list comprehension and joining it with empty string:
>>> print "".join(word[:2].lower() for word in namelist)
jodo
To see how it's working in smaller steps:
>>> firsts = [word[:2].lower() for word in namelist]
>>> firsts
['jo', 'do']
>>> print "".join(firsts)
jodo
The print "magic comma" always inserts spaces, so you can't do things this way.
You have three choices:
Join the words up into a string first, then print that string: print ''.join(word[:2].lower() for word in namelist).
Write directly to stdout instead of using print: sys.stdout.write(word[:2].lower())
Use Python 3-style print, which can do things this way. First, from __future__ import print_function at the top of your code. Then, print(word[:2].lower(), end='').
>>> fullname = "John Doe"
>>> words = fullname.lower().split()
>>> words
['john', 'doe']
>>> print("".join(x[:2] for x in words))
jodo
[:2] selects 1st two letter . lower converts them to lowercase.using + you can concatenate string.
python 2.x:
>>> print "".join(x[:2] for x in words)
The print function from Python 3 has a parameter sep (for "separator") which can be set to a null string. Using that and using the * operator to specify passing in a variable number of arguments:
from __future__ import print_function
fullname = "John Doe"
words = (word[:2].lower() for word in fullname.split())
print(*words, sep='')
I have this code:
filenames=["file1","FILE2","file3","fiLe4"]
def alignfilenames():
#build a string that can be used to add labels to the R variables.
#format goal: suffixes=c(".fileA",".fileB")
filestring='suffixes=c(".'
for filename in filenames:
filestring=filestring+str(filename)+'",".'
print filestring[:-3]
#now delete the extra characters
filestring=filestring[-1:-4]
filestring=filestring+')'
print "New String"
print str(filestring)
alignfilenames()
I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get:
suffixes=c(".file1",".FILE2",".file3",".fiLe4"
New String
)
Any idea what's going on or how to fix it?
Does this do what you want?
>>> filenames=["file1","FILE2","file3","fiLe4"]
>>> c = "suffixes=c(%s)" % (",".join('".%s"' %f for f in filenames))
>>> c
'suffixes=c(".file1",".FILE2",".file3",".fiLe4")'
Using a string.join is a much better way to add a common delimiter to a list of items. It negates the need to have to check for being on the last item before adding the delimiter, or in your case attempting to strip off the last one added.
Also, you may want to look into List Comprehensions
It looks like you might be trying to use python to write an R script, which can be a quick solution if you don't know how to do it in R. But in this case the R-only solution is actually rather simple:
R> filenames= c("file1","FILE2","file3","fiLe4")
R> suffixes <- paste(".", tolower(filenames), sep="")
R> suffixes
[1] ".file1" ".file2" ".file3" ".file4"
R>
What's going on is that this slicing returns an empty string
filestring=filestring[-1:-4]
Because the end is before the begin. Try the following on the command line:
>>> a = "hello world"
>>> a[-1:-4]
''
The solution is to instead do
filestring=filestring[:-4]+filestring[-1:]
But I think what you actually wanted was to just drop the last three characters.
filestring=filestring[:-3]
The better solution is to use the join method of strings as sberry2A suggested