2

I want to print values from a dictionary without any spacing.

This is a test of my code:

d = {}
d["char12"] = "test"
d["char22"] = "test"
print d["char12"],
print d["char22"]

the output is

test test

but i need it to be:

testtest

is there a way to remove that automatic spacing?

Thanks!

5 Answers5

4

Option 1: combine the print statements

print d["char12"]+d["char22"]

Option 2: use stdout.write

import sys
...
sys.stdout.write(d["char12"]) # write without a separator
print d["char22"]
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

str.format() is one of the many options.

From the documentation:

This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

You use it like this:

print '{}{}'.format(d["char12"], d["char22"])

This will also work:

print('{char12}{char22}'.format(**d))

which lets you use the dictionary keys in the format string.

mhawke
  • 84,695
  • 9
  • 117
  • 138
1

You could use join()

d = {}
d["char12"] = "test"
d["char22"] = "test"

print ''.join((d["char12"], d["char22"]))

output: testtest

Simon
  • 9,762
  • 15
  • 62
  • 119
0

One way:

import sys
d = {}
d["char12"] = "test"
d["char22"] = "test"
sys.stdout.write(d["char12"])
sys.stdout.write(d["char22"])

You can use this!

Or you can use another way:

from __future__ import print_function
d = {}
d["char12"] = "test"
d["char22"] = "test"
print(d["char12"], end="")
print(d["char22"], end="")
PRVS
  • 1,612
  • 4
  • 38
  • 75
-1

To print a dictionary's values without spaces:

print(''.join(d.values())

Dictionaries are not ordered, so if order is important, you should use an OrderedDict.

from collections import OrderedDict

d = OrderedDict()
d["char12"] = "test"
d["char22"] = "test"

print(''.join(d.values())
Adam Holloway
  • 413
  • 4
  • 7
  • There's nothing wrong with using `join()`, but it's probably not a good idea to select your data structure on the basis of being able to print out its values without spaces. – mhawke Feb 02 '16 at 09:04