How to replace space in a string with \n
Michael Poeltl
michael.poeltl at univie.ac.at
Thu Jan 31 06:17:40 EST 2019
hi ^Bert,
I've just thought that you don't like to use text.replace(' ', '\n'), and so I came up with another way to get the job done.
So it was part of a "school-test" - uiuitststs ;-)
follow the hint from Peter then, and inside *your* for-loop ask yourself, how to inspect the value of c in a loop and what to do *if* the value of c was ' ' .
as mentioned, a string is immuteable, so you cannot change it *inplace* - you have to build a new str-object (has a new object-id the starting with an empty string say
newtext = ''
and with each loop over your original text you add one character like
newtext = newtext+c
and only if c has a value of ' ', then you add a different value like '\n'
well, now you should try to understand peters for-loop, and then you should try to combine what you have learned with the if-statement within the for(-loop) block
happy learning the python-language! It's a great one, this I can promise you!
regards
Michael
* Peter Otten <__peter__ at web.de> [2019-01-31 11:15]:
> ^Bart wrote:
>
> >> Why?
> >
> > It's a school test, now we should use just what we studied, if than,
> > else, sequences, etc.!
> >
> > ^Bart
>
> Hint: you can iterate over the characters of a string
>
> >>> for c in "hello":
> ... print(c)
> ...
> h
> e
> l
> l
> o
>
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
--
Michael Poeltl <michael.poeltl at univie.ac.at>
Computational Materials Physics at University
Wien, Sensengasse 8/12, A-1090 Wien, AUSTRIA
http://cmp.univie.ac.at/
http://homepage.univie.ac.at/michael.poeltl/
using elinks-0.12, mutt-1.5.21, and vim-7.4,
with python-3.6.1, on linux mint 17.3 (rose) :-)
fon: +43-1-4277-51409
"Lehrend lernen wir!"
More information about the Python-list
mailing list