Removing spaces from For Loop in Python - python

When creating a for loop, it appears that python adds spaces.
menuItems = ['apple', 'banana', 'car', 'thing', 'whatever', 'burrito']
menuNum = 1
for menuItem in menuItems:
print menuNum,'. ',menuItem
menuNum = menuNum + 1
returns this
1 . apple
2 . banana
3 . car
etc...
Any idea on how I can simply get this without the spacing?
eg.
1. apple
2. banana
3. car

Use string formatting. print in Python 2 puts a space for each comma used to separate the items.
>>> data = ['apple', 'banana', 'car', 'thing', 'whatever', 'burrito']
for i, item in enumerate(data, 1):
print '{}. {}'.format(i, item)
...
1. apple
2. banana
3. car
4. thing
5. whatever
6. burrito
And use enumerate if you want index as well items.

Use one of Python's formatting capabilities.
print "{} . {}".format(menuNum, menuItem) # 2.7+ or 3.x
print "%d . %s" % (menuNum, menuItem)

The print expression in Python 2 puts spaces between the items on a single line. To avoid this, create a single string first that looks like you want to output to appear:
# string formatting
for menuItem in menuItems:
print '{0}. {1}'.format(menuNum, menuItem)
Or else, use the Python3 print function, which has more options available.
# print function
from __future__ import print_function
for menuItem in menuItems:
print(menuNum, '. ', menuItem, sep='')

Just use:
from __future__ import print_function
print(menuNum, '. ', menuItem, sep='')
You could also use string formatting:
print '{0}. {1}'.format(menuNum, menuItem)

You have a space after the ". " when using a comma and printing, a space is inserted for you.
Altough I use python 3.3, as far as I'm aware, using '+' should still work. Unless I'm missing something; the following would work fine.
print menuNum + '.' + menuItem

Related

Python 3.5: Is there a way to make this list more organized?

Say you have the following code:
bicycles = ['Trek','Cannondale','Redline','Secialized']
print(bicycles[0],bicycles[1],bicycles[2],bicycles[3])
This would print out:
Trek Cannondale Redline Specialized
I have two questions. First, Is there a way to make the print string more organized so that you don't have to type out bicycles multiple times? I know that if you were to just do:
print(bicycles)
It would print the brackets also, which I'm trying to avoid.
Second question, how would I insert commas to display within the list when its printed?
This is how I would like the outcome:
Trek, Cannondale, Redline, Specialized.
I know that I could just do
print("Trek, Cannondale, Redline, Specialized.")
But using a list, is there anyway to make it more organzed? Or would printing the sentence out be the smartest way of doing it?
use .join() method:
The method join() returns a string in which the string elements of
sequence have been joined by str separator.
syntax: str.join(sequence)
bicycles = ['Trek','Cannondale','Redline','Secialized']
print (' '.join(bicycles))
output:
Trek Cannondale Redline Secialized
Example: change separotor into ', ':
print (', '.join(bicycles))
output:
Trek, Cannondale, Redline, Secialized
For python 3. you can also use unpacking:
We can use * to unpack the list so that all elements of it can be
passed as different parameters.
We use operator *
bicycles = ['Trek','Cannondale','Redline','Secialized']
print (*bicycles)
output:
Trek Cannondale Redline Secialized
NOTE:
It's using ' ' as a default separator, or specify one, eg:
print(*bicycles, sep=', ')
Output:
Trek, Cannondale, Redline, Secialized
It will also work if the elements in the list are different types (without having to explicitly cast to string)
eg, if bicycles was ['test', 1, 'two', 3.5, 'something else']
bicycles = ['test', 1, 'two', 3.5, 'something else']
print(*bicycles, sep=', ')
output:
test, 1, two, 3.5, something else
You can use join:
' '.join(bicycles)
', '.join(bicycles)

Remove whitespace before a specific character in python?

I was wondering if you knew the best way to do this.
This program uses OCR to read text. Occasionally, spaces appear before a decimal point like so:
{'MORTON BASSET BLK SESAME SEE': '$6.89'}
{"KELLOGG'S RICE KRISPIES": '$3.49'}
{'RAID FLY RIBBON 4PK': '$1 .49'}
as you can see, a space appears before the decimal point on the last entry. Any ideas on how to strip JUST this whitespace?
Thank you :)
EDIT: contents before decimal point may contain a varying amount of whitespace. Like
$1 .49
$1 .49
$1 .49
Use regular expressions.
import re
a_list = {"1 .49", "1 .49", "1 .49"}
for a in a_list:
print re.sub(' +.', '.', a)
Result will be
1.49
1.49
1.49
You can just strip out all whitespace from the string, assuming that they follow the same format. SOmething like this:
for item in items:
for key in item.keys():
item[key] = item[key].replace(" ", "")
The key part is replacing the whitespace with no whitespace.
If you just want the whitespace before the ".", then you could use:
.replace(" .", ".") instead.
This would only replace 1 white space. To replace multiple, you could use a while loop like this:
while ' .' in item[key]:
item[key].replace(' .', '.')
For your dict obj:-
>>> d = {'RAID FLY RIBBON 4PK': '$1 .49'}
>>> d['RAID FLY RIBBON 4PK'] = d['RAID FLY RIBBON 4PK'].replace(' ','')
>>> d
{'RAID FLY RIBBON 4PK': '$1.49'}
Even if there is varying space; replace would work fine. See this:-
>>> d = {'RAID FLY RIBBON 4PK': '$1 .49'}
>>> d['RAID FLY RIBBON 4PK'] = d['RAID FLY RIBBON 4PK'].replace(' ','')
>>> d
{'RAID FLY RIBBON 4PK': '$1.49'}
This is trivial with split and join:
"".join("1 .49".split())
This works because splits on one or more spaces. To do this for each value in a dictionary:
{k, "".join(v.split()) for k,v in dict_.items()}
i think that maybe you want something more generic not only for that key:
for key, value in d.items():
d[key]=value.replace(" ","")
in this way independent of the key othe number of space the result will be without white spaces
Sure:
string.replace(' .', '')

How to "properly" display a list in python without brackets

currently I am using
for s in list:
print(*s)
but it displays the list output as
['this is']
['the output']
But I would like the output to be displayed as
this is
the output
There should be a simple solution but i am still yet to come across one.
l = [['this is'], ['the output']]
for sub_list in l:
print(sub_list[0])
list_string = ', '.join(list_name)
print (list_string) #without brackets
Join using the newline character:
print("\n".join(your_list))
Please note that list is a Python type and shouldn't be used as a variable name.

Remove brackets [] from list (while sorting with key)

What i am after: instead of having a list output like this:
['test1', 'test2', test3']
i would want it to output like this:
test1 | test2 | test3 or this is fine too test1, test2, test3
My code: right now this is how it looks like:
deelnemers = []
# i add name, csgo and score to deelnemers[] via class Deelnemer
deelnemers.append(Deelnemer(naam, int(csgo), int(score)))
# key to sort it by csgo value
def keyCSGO(deelnemer):
return deelnemer.csgo
# i print it in reverse so the highest csgo number will be first
print("\nNaam | CSGO Score\n----------------\n", sorted(deelnemers, key=keyCSGO, reverse=True))
What i have tried:
print(", ".join("\nNaam | CSGO Score\n----------------\n", sorted(deelnemers, key=keyCSGO, reverse=True)))
so obviously the above gives that you can have only 1 argument with .join: join() takes exactly one argument (2 given)
so i removed the naam | csgo part to test it out:
print(", ".join(sorted(deelnemers, key=keyCSGO, reverse=True)))
but now i get this exception: sequence item 0: expected str instance, Deelnemer found
i think i am looking in the wrong direction, so i am not sure where to look at to have [ '' ] removed from a list. Thank you for the help and advice.
str.join can only join strings. Hopefully the Deelnemer class has a __str__ method defined, then you can do:
print("Naam | CSGO Score\n----------------")
print(", ".join(map(str, sorted(deelnemers, key=keyCSGO, reverse=True))))
Alternative to using str.join is to let print do more of the work for you; it's happy to stringify and insert separators:
from operator import attrgetter
# Print header normally, but let print handle the newlines and separate lines
# so alignment of header and bar more obvious
# You original code was one hyphen short (which I fixed)
print("Naam | CSGO Score",
"-----------------", sep="\n")
# Use *-unpacking to convert sorted list to sequential positional arguments
# and pass sep=', ' to replace default sep of ' '.
# Use attrgetter instead of rolling your own key function
print(*sorted(deelnemers, key=attrgetter('csgo'), reverse=True), sep=', ')
You can only join strings, so you probably need to access the name attribute (assuming that what it is) of each instance after sorting to use them in join:
print(", ".join(d.name for d in sorted(deelnemers, key=keyCSGO, reverse=True)))
You can also put the attributes in a string before joining using string formatting (credits #Tadhg):
", ".join("{0.name} {0.csgo} {0.score}".format(d) for d in sorted(deelnemers, key=keyCSGO, reverse=True))

String formatting in Python -textwrapper

I have a list of People=[Tom,Mike,Carol] and I want to print it in the the below format.
People Tom
Mike
Carol
Basically its the Title (People) some fixed tabs and then a list of the name in new line ( it sorta looks like a table). I want to achieve this using textwrap in Python but if there is any other possibility, I am open to that as well.
dedented_text = textwrap.dedent(' This is a test sentecne to see how well the textwrap works and hence using it here to test it').strip()
for width in [ 20 ]:
h='{0: <4}'.format('f')
k='{0: >4}'.format(textwrap.fill(dedented_text, width=20))
print h+k
Output:
f This is a test
sentecne to see how
well the textwrap
works and hence
using it here to
test it
Above i added my code for printing the Category and a sentence. But i'm not able to achieve what I want
Just print the first line separately then print the others in a loop:
print 'People ' + people[0]
for i in range(1, len(people)):
print ' ' * 7 + people[i]

Categories

Resources