Reputation: 397
Might be a simple fix but I've tried everything. I'm trying to join and print the values from my 2d array in a single string without each character being separated if not separated by an actual space. For example what my code does now "H E L L O W O R L D" instead of "HELLO WORLD". Can someone please help.
for a in range(int(numOfColumns)):
for b in range(numOfRows):
#''.join(Matric[b][a])
#print(Matrix[b][a]),
#print(Matrix[b][a]),
Upvotes: 0
Views: 605
Reputation: 3790
You can use a list comprejesions:
result = " ".join(["".join([i for i in row]) for row in Matrix])
Or just
result = " ".join(["".join(row) for row in Matrix])
as @Tomothy32 noted.
Here an expression
"".join(row)
which creates a string from a row, for example:
row = ['h', 'e', 'l', 'l', 'o']
"".join([row])
Out:
hello
Almost the same for the outer loop which iterates the row, but it joins the strings with a whitespaces:
result = " ".join(...)
Or you can do it step-by-step, but it's not so clear:
substrings = []
for row in Matrix:
substr = ""
for char in row:
substr += char
substrings.append(substr)
result = " ".join(substrings)
I don't know how to do that easily without comprehensions. Probably you should use it.
Edit
How it works:
Matrix = [
['H', 'e', 'l', 'l', 'o'], # it's a first row
['w', 'o', 'r', 'l', 'd'] # it's a second row
]
Python iterastes trough the outer level first, i.e.
[print(row) for row in Matrix]
will print something like that:
['H', 'e', 'l', 'l', 'o'],
['w', 'o', 'r', 'l', 'd']
each row is a list (in this case). So, we can iterate through it, using inner loop (list comprehension):
[[print(i, end='') for i in row]) for row in Matrix]
Out:
"hello"
"world"
(end=''
just cahnges newline to the empty string). Now you can change print to the "".join
method and get what you want.
How iterate columns? Well, it's not so easy, especially when lengths of the strings are different. If the length is equal, you could use dollowing comprehension (answered here):
[[row(i) for row in matrix] for i in range(max(len(r) for r in Matrix))]
Out:
[['h', 'w'],
['e', 'o'],
['l', 'r'],
['l', 'l'],
['o', 'd']]
But probably it's easier to generate you data already transposed. There are some tutorials about a comprehensions, you can read it, for example, this one. Comprehensions is a very useful tool.
Upvotes: 2
Reputation: 592
Assuming below martix:
Matric = [['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']]
mat = ''
for x in Matric[0]:
mat = ''.join([mat,x])
mat += ' '
for y in Matric[1]:
mat = ''.join([mat, y])
print(mat)
Upvotes: 0