Printing lists in python without spaces - python

I am doing a program that changes a number in base 10 to base 7, so i did this :
num = int(raw_input(""))
mod = int(0)
list = []
while num> 0:
mod = num%7
num = num/7
list.append(mod)
list.reverse()
for i in range (0,len(list)):
print list[i],
But if the number is 210 it prints 4 2 0 how do i get rid of the spaces

You can use join with list comprehension:
>>> l=range(5)
>>> print l
[0, 1, 2, 3, 4]
>>> ''.join(str(i) for i in l)
'01234'
Also, don't use list as a variable name since it is a built-in function.

In python 3 you can do like this :
print(*range(1,int(input())+1), sep='')
Your output will be like this if input = 4 :
1234

Convert the list to a string, and replace the white spaces.
strings = ['hello', 'world']
print strings
>>>['hello', 'world']
print str(strings).replace(" ", "")
>>>['hello','world']

Take a look at sys.stdout. It's a file object, wrapping standard output. As every file it has write method, which takes string, and puts it directly to STDOUT. It also doesn't alter nor add any characters on it's own, so it's handy when you need to fully control your output.
>>> import sys
>>> for n in range(8):
... sys.stdout.write(str(n))
01234567>>>
Note two things
you have to pass string to the function.
you don't get newline after printing.
Also, it's handy to know that the construct you used:
for i in range (0,len(list)):
print list[i],
is equivalent to (frankly a bit more efficient):
for i in list:
print i,

Doing the following worked for me in Python3
print(*list,sep='')

You can use below code snippet for python3
print(*list(range(1, n + 1)), sep='')
* will remove initial and end character like [{}]
sep = '' will remove the spaces between item.

Use list_comprehension.
num= int(raw_input(""))
mod=int(0)
list =[]
while num> 0:
mod=num%7
num=num/7
list.append(mod)
list.reverse()
print ''.join([str(list[i]) for i in range (0,len(list))])

The print() function has an argument to specify the end character which by default is '\n'. Specifying the end character as '' and printing using a loop will do what you are looking for:
n_list = [1,2,3,4,5]
for i in n_list:
print(i, end='')

s = "jay"
list = [ i for i in s ]
It you print list you will get:
['j','a','y']
new_s = "".join(list)
If you print new_s:
"jay"

Related

Python Zipfile read file and output each line instead of text block? [duplicate]

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))

Pass arguments to Print [duplicate]

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))

How to combine individual characters in one string in python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 6 years ago.
I have code like this:
def reverse(text):
l=len(text)
while ((l-1)!=0):
print (str(text[l-1]))
l=l-1
print (str(text[0]))
a=reverse("abc!de#fg")
The output is:
g
f
#
e
d
!
c
b
a
but I want to combine these individual characters and want out put like this:
gf#ed!cba
To print without the newline at the end of each line do:
print('text', end='')
To take a list of characters and make them one string, do:
''.join(list_of_characters)
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
print (reverse('abc!de#fg'))
The simplest way to reverse a string:
In [1]: a = "abc!de#fg"
In [2]: print(a[::-1])
gf#ed!cba
The python print statement adds a newline by default. An easy way to print without newlines is
sys.stdout.write('some text')
# or
print('some text', end='')
You will need to concatenate them and then print the string result.
This is because the function print automatically does a break line.
A fix would be:
def reverse(text):
l = len(text)
aux = ''
while l-1 != 0:
aux += str(text[l-1])
l = l - 1
print (aux)
a = reverse("abc!de#fg")`
P.S: Try to avoid redundant parenthesis =)
Hey try to put the print value in variable and print that at the end. Like this.
def reverse(text):
l=len(text)
output = ""
while ((l-1)!=0):
output += (str(text[l-1]))
l=l-1
output +=(str(text[0]))
print output
a=reverse("abc!de#fg")
Hope this helps
In Python, the simplest way to reverse a Sequence is with a slice:
>>> string="abc!de#fg"
>>> print(string[::-1])
gf#ed!cba
Slicing will give you a copy of the sequence in reverse order.
In general, you want a function to do one thing. Returning a value and printing some output are separate concerns, so they should not be conflated in the same function. If you have a function that returns a reversed string, you can simply print the function:
print(reverse("abc"))
Then, you can see that your actual algorithm is fine, if not entirely Pythonic:
def reverse(text):
l=len(text)
output = ""
while ((l-1)!=0):
output += (str(text[l-1]))
l=l-1
output +=(str(text[0]))
return output
You can clearly see now that it's the print function in your way.

python string manipulation

I have a string s with nested brackets: s = "AX(p>q)&E((-p)Ur)"
I want to remove all characters between all pairs of brackets and store in a new string like this: new_string = AX&E
i tried doing this:
p = re.compile("\(.*?\)", re.DOTALL)
new_string = p.sub("", s)
It gives output: AX&EUr)
Is there any way to correct this, rather than iterating each element in the string?
Another simple option is removing the innermost parentheses at every stage, until there are no more parentheses:
p = re.compile("\([^()]*\)")
count = 1
while count:
s, count = p.subn("", s)
Working example: http://ideone.com/WicDK
You can just use string manipulation without regular expression
>>> s = "AX(p>q)&E(qUr)"
>>> [ i.split("(")[0] for i in s.split(")") ]
['AX', '&E', '']
I leave it to you to join the strings up.
>>> import re
>>> s = "AX(p>q)&E(qUr)"
>>> re.compile("""\([^\)]*\)""").sub('', s)
'AX&E'
Yeah, it should be:
>>> import re
>>> s = "AX(p>q)&E(qUr)"
>>> p = re.compile("\(.*?\)", re.DOTALL)
>>> new_string = p.sub("", s)
>>> new_string
'AX&E'
Nested brackets (or tags, ...) are something that are not possible to handle in a general way using regex. See http://www.amazon.de/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/ref=sr_1_1?ie=UTF8&s=gateway&qid=1304230523&sr=8-1-spell for details why. You would need a real parser.
It's possible to construct a regex which can handle two levels of nesting, but they are already ugly, three levels will already be quite long. And you don't want to think about four levels. ;-)
You can use PyParsing to parse the string:
from pyparsing import nestedExpr
import sys
s = "AX(p>q)&E((-p)Ur)"
expr = nestedExpr('(', ')')
result = expr.parseString('(' + s + ')').asList()[0]
s = ''.join(filter(lambda x: isinstance(x, str), result))
print(s)
Most code is from: How can a recursive regexp be implemented in python?
You could use re.subn():
import re
s = 'AX(p>q)&E((-p)Ur)'
while True:
s, n = re.subn(r'\([^)(]*\)', '', s)
if n == 0:
break
print(s)
Output
AX&E
this is just how you do it:
# strings
# double and single quotes use in Python
"hey there! welcome to CIP"
'hey there! welcome to CIP'
"you'll understand python"
'i said, "python is awesome!"'
'i can\'t live without python'
# use of 'r' before string
print(r"\new code", "\n")
first = "code in"
last = "python"
first + last #concatenation
# slicing of strings
user = "code in python!"
print(user)
print(user[5]) # print an element
print(user[-3]) # print an element from rear end
print(user[2:6]) # slicing the string
print(user[:6])
print(user[2:])
print(len(user)) # length of the string
print(user.upper()) # convert to uppercase
print(user.lstrip())
print(user.rstrip())
print(max(user)) # max alphabet from user string
print(min(user)) # min alphabet from user string
print(user.join([1,2,3,4]))
input()

`' '.join(e)` isn't changing value of e

I'm creating a function to create all 26 combinations of words with a fixed suffix. The script works except for the JOIN in the second-to-last line.
def create_word(suffix):
e=[]
letters="abcefghijklmnopqrstuvwxyz"
t=list(letters)
for i in t:
e.append(i)
e.append(suffix)
' '.join(e)
print e
Currently, it is printing ['a', 'suffix', 'b', 'suffix, ...etc]. And I want it to print out as one long string: 'aSuffixbSuffixcSuffix...etc.' Why isn't the join working in this? How can I fix this?
In addition, how would I separate the characters once I have the string? For example to translate "take the last character of the suffix and add a space to it every time ('aSuffixbSuffixcSuffix' --> 'aSuffix bSuffix cSuffix')". Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).
str.join returns the new value, not transform the existing one. Here's one way to accomplish it.
result = ' '.join(e)
print result
But if you're feeling clever, you can streamline a lot of the setup.
import string
def create_word(suffix):
return ' '.join(i + suffix for i in string.ascii_lowercase)
join doesn't change its arguments - it just returns a new string:
result = ' '.join(e)
return result
If you really want the output you specified (all of the results concatenated together):
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> letters = string.ascii_lowercase
>>> suffix = 'Suffix'
>>> ''.join('%s%s' % (l, suffix) for l in letters)
'aSuffixbSuffixcSuffixdSuffixeSuffixfSuffixgSuffixhSuffixiSuffixjSuffixkSuffixlSuffixmSuffixnSuffixoSuffixpSuffixqSuffixrSuffixsSuffixtSuffixuSuffixvSuffixwSuffixxSuffixySuffixzSuffix'
Beside the problem already mentioned by rekursive, you should have a look at list comprehension:
def create_word(suffix):
return ''.join(
[i+suffix for i in "abcefghijklmnopqrstuvwxyz"]
)
print create_word('suffix')

Categories