What I want
sentence = ["This","is","a","short","sentence"]
# Desired Output
T h i s
i s
a
s h o r t
s e n t e n c e
>>>
What I tried
sentence = [row.replace[""," "] for row in sentence]
for item in sentence:
print[item]
The problem with this is that it prints a space at the beginning and end of every line but I only want a space between each letter
asked Nov 3, 2018 at 23:17
You could use str.join[]
sentence = ["This","is","a","short","sentence"]
for w in sentence:
print[' '.join[w]]
answered Nov 3, 2018 at 23:20
SpghttCdSpghttCd
10.1k2 gold badges18 silver badges24 bronze badges
1
You could use the facts that a string is a sequence, a sequence can be split into its items with the splat *
operator, and and the print
function prints items by default separated by spaces. Those three facts can be combined into one short line, print[*word]
, if word
is a string.
So you can use
sentence = ["This","is","a","short","sentence"]
for word in sentence:
print[*word]
This gives the printout
T h i s
i s
a
s h o r t
s e n t e n c e
answered Nov 3, 2018 at 23:26
Rory DaultonRory Daulton
21k5 gold badges39 silver badges48 bronze badges
2
Not the answer you're looking for? Browse other questions tagged python list for-loop or ask your own question.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
In this article, we will learn about how to print space or multiple spaces in the Python programming language. Spacing in Python language is quite simple than other programming language. In C languages, to print 10 spaces a loop is used while in python no loop is used to print number of spaces.
Following are the example of the print spaces:
Example 1: A simple way to print spaces
Python3
print
[
"GeeksForGeeks"
]
print
[
' '
]
print
[
" "
]
print
[
"Geeks For Geeks"
]
Output:
GeeksForGeeks Geeks For Geeks
Example 2: Printing spaces between two values while printing in a single print statement.
Python3
x
=
1
y
=
2
print
[
"x:"
,x]
print
[
"y:"
,y]
print
[x,
"+"
,y,
"="
,x
+
y]
Output:
x: 1 y: 2 1 + 2 = 3
Example 3: Print multiple spaces between two values.
Python3
print
[
"Geeks"
+
" "
+
"For"
+
" "
+
"Geeks"
]
print
[
"Geeks"
,
"For"
,
"Geeks"
]
print
[
"Geeks"
+
" "
*
3
+
"For"
+
" "
*
3
+
"Geeks"
]
print
[
"Geeks"
+
" "
*
5
+
"For"
+
" "
*
10
+
"Geeks"
]
Output:
Geeks For Geeks Geeks For Geeks Geeks For Geeks Geeks For Geeks