Replace() method not working within functionHow to read a file line-by-line into a list?rn, r and n what is the difference between them?Calling a function of a module by using its name (a string)Replacements for switch statement in Python?How to flush output of print function?Difference between append vs. extend list methods in PythonUsing global variables in a functionUnderstanding Python super() with __init__() methodsStatic methods in Python?How to make a chain of function decorators?Does Python have a string 'contains' substring method?Replacing lines of output with custom message

"You are your self first supporter", a more proper way to say it

Can I make popcorn with any corn?

How does quantile regression compare to logistic regression with the variable split at the quantile?

When a company launches a new product do they "come out" with a new product or do they "come up" with a new product?

Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)

What's the output of a record needle playing an out-of-speed record

Paid for article while in US on F-1 visa?

How old can references or sources in a thesis be?

Can a vampire attack twice with their claws using Multiattack?

What does it mean to describe someone as a butt steak?

Could an aircraft fly or hover using only jets of compressed air?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

How does one intimidate enemies without having the capacity for violence?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Why is 150k or 200k jobs considered good when there's 300k+ births a month?

How much RAM could one put in a typical 80386 setup?

How can I make my BBEG immortal short of making them a Lich or Vampire?

Codimension of non-flat locus

Why can't I see bouncing of a switch on an oscilloscope?

What does the "remote control" for a QF-4 look like?

Modeling an IP Address

Add text to same line using sed

What is a clear way to write a bar that has an extra beat?

Malcev's paper "On a class of homogeneous spaces" in English



Replace() method not working within function


How to read a file line-by-line into a list?rn, r and n what is the difference between them?Calling a function of a module by using its name (a string)Replacements for switch statement in Python?How to flush output of print function?Difference between append vs. extend list methods in PythonUsing global variables in a functionUnderstanding Python super() with __init__() methodsStatic methods in Python?How to make a chain of function decorators?Does Python have a string 'contains' substring method?Replacing lines of output with custom message






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I am making a function that accepts a plain text file and then returns a list of words in that file. Obviously, I would like to get rid of any newline 'n', however, when using '.replace()' nothing happens.



Function:



textfile = 'name.txt'

def read_words(filename):
f = open(filename,'r')
message = f.read()
a = message.replace('n', '')
wordlist = a.split(' ')
print(wordlist)

read_words(textfile)


Sample txt:



Thisnnisnnnannnmynnwfile with spaces and blanks


My output:



['This\n\nis\n\n\na\n\n\nmy\n\nwfile', 'with', 'spaces', 'and', 'blanks']


Why is the '.replace()' method not working?










share|improve this question



















  • 2





    The replace method is certainly working. What's your expected output?

    – blhsing
    Mar 9 at 1:25






  • 2





    Why is the '.replace()' method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything.

    – John Gordon
    Mar 9 at 1:26







  • 5





    Is sample txt literally the string Thisnnisnnnannnmynnwfile with spaces and blanks, or are you replacing the newlines with n for us? If the former, you'll need to escape the backslash in your replace: message.replace('\n', '')

    – Dillon Davis
    Mar 9 at 1:28







  • 1





    How does one input the single character 'n' in a txt file?

    – Okeh
    Mar 9 at 1:29






  • 2





    @DillonDavis Happy to accept an answer of yours if you post one

    – Okeh
    Mar 9 at 1:45

















2















I am making a function that accepts a plain text file and then returns a list of words in that file. Obviously, I would like to get rid of any newline 'n', however, when using '.replace()' nothing happens.



Function:



textfile = 'name.txt'

def read_words(filename):
f = open(filename,'r')
message = f.read()
a = message.replace('n', '')
wordlist = a.split(' ')
print(wordlist)

read_words(textfile)


Sample txt:



Thisnnisnnnannnmynnwfile with spaces and blanks


My output:



['This\n\nis\n\n\na\n\n\nmy\n\nwfile', 'with', 'spaces', 'and', 'blanks']


Why is the '.replace()' method not working?










share|improve this question



















  • 2





    The replace method is certainly working. What's your expected output?

    – blhsing
    Mar 9 at 1:25






  • 2





    Why is the '.replace()' method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything.

    – John Gordon
    Mar 9 at 1:26







  • 5





    Is sample txt literally the string Thisnnisnnnannnmynnwfile with spaces and blanks, or are you replacing the newlines with n for us? If the former, you'll need to escape the backslash in your replace: message.replace('\n', '')

    – Dillon Davis
    Mar 9 at 1:28







  • 1





    How does one input the single character 'n' in a txt file?

    – Okeh
    Mar 9 at 1:29






  • 2





    @DillonDavis Happy to accept an answer of yours if you post one

    – Okeh
    Mar 9 at 1:45













2












2








2








I am making a function that accepts a plain text file and then returns a list of words in that file. Obviously, I would like to get rid of any newline 'n', however, when using '.replace()' nothing happens.



Function:



textfile = 'name.txt'

def read_words(filename):
f = open(filename,'r')
message = f.read()
a = message.replace('n', '')
wordlist = a.split(' ')
print(wordlist)

read_words(textfile)


Sample txt:



Thisnnisnnnannnmynnwfile with spaces and blanks


My output:



['This\n\nis\n\n\na\n\n\nmy\n\nwfile', 'with', 'spaces', 'and', 'blanks']


Why is the '.replace()' method not working?










share|improve this question
















I am making a function that accepts a plain text file and then returns a list of words in that file. Obviously, I would like to get rid of any newline 'n', however, when using '.replace()' nothing happens.



Function:



textfile = 'name.txt'

def read_words(filename):
f = open(filename,'r')
message = f.read()
a = message.replace('n', '')
wordlist = a.split(' ')
print(wordlist)

read_words(textfile)


Sample txt:



Thisnnisnnnannnmynnwfile with spaces and blanks


My output:



['This\n\nis\n\n\na\n\n\nmy\n\nwfile', 'with', 'spaces', 'and', 'blanks']


Why is the '.replace()' method not working?







python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 1:28







Okeh

















asked Mar 9 at 1:20









OkehOkeh

706




706







  • 2





    The replace method is certainly working. What's your expected output?

    – blhsing
    Mar 9 at 1:25






  • 2





    Why is the '.replace()' method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything.

    – John Gordon
    Mar 9 at 1:26







  • 5





    Is sample txt literally the string Thisnnisnnnannnmynnwfile with spaces and blanks, or are you replacing the newlines with n for us? If the former, you'll need to escape the backslash in your replace: message.replace('\n', '')

    – Dillon Davis
    Mar 9 at 1:28







  • 1





    How does one input the single character 'n' in a txt file?

    – Okeh
    Mar 9 at 1:29






  • 2





    @DillonDavis Happy to accept an answer of yours if you post one

    – Okeh
    Mar 9 at 1:45












  • 2





    The replace method is certainly working. What's your expected output?

    – blhsing
    Mar 9 at 1:25






  • 2





    Why is the '.replace()' method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything.

    – John Gordon
    Mar 9 at 1:26







  • 5





    Is sample txt literally the string Thisnnisnnnannnmynnwfile with spaces and blanks, or are you replacing the newlines with n for us? If the former, you'll need to escape the backslash in your replace: message.replace('\n', '')

    – Dillon Davis
    Mar 9 at 1:28







  • 1





    How does one input the single character 'n' in a txt file?

    – Okeh
    Mar 9 at 1:29






  • 2





    @DillonDavis Happy to accept an answer of yours if you post one

    – Okeh
    Mar 9 at 1:45







2




2





The replace method is certainly working. What's your expected output?

– blhsing
Mar 9 at 1:25





The replace method is certainly working. What's your expected output?

– blhsing
Mar 9 at 1:25




2




2





Why is the '.replace()' method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything.

– John Gordon
Mar 9 at 1:26






Why is the '.replace()' method not working? Show us the output that makes you think it isn't working. You've only shown us the sample file contents, which doesn't demonstrate anything.

– John Gordon
Mar 9 at 1:26





5




5





Is sample txt literally the string Thisnnisnnnannnmynnwfile with spaces and blanks, or are you replacing the newlines with n for us? If the former, you'll need to escape the backslash in your replace: message.replace('\n', '')

– Dillon Davis
Mar 9 at 1:28






Is sample txt literally the string Thisnnisnnnannnmynnwfile with spaces and blanks, or are you replacing the newlines with n for us? If the former, you'll need to escape the backslash in your replace: message.replace('\n', '')

– Dillon Davis
Mar 9 at 1:28





1




1





How does one input the single character 'n' in a txt file?

– Okeh
Mar 9 at 1:29





How does one input the single character 'n' in a txt file?

– Okeh
Mar 9 at 1:29




2




2





@DillonDavis Happy to accept an answer of yours if you post one

– Okeh
Mar 9 at 1:45





@DillonDavis Happy to accept an answer of yours if you post one

– Okeh
Mar 9 at 1:45












2 Answers
2






active

oldest

votes


















1














The issue with your current text replacement is that is considered an escape character- the literal characters n are interpreted as a newline character instead. To solution to this is to escape the character itself, via \. Your updated replace statement would then read:



a = message.replace('\n', '')


instead of:



a = message.replace('n', '')





share|improve this answer






























    1














    This might be case that python or some other programming languages reads new line as 'n' escape character. So when python reads your file 'n' means new line and '\n' means actual 'n' character you wrote in the text file.



    So you need to replace like
    a = message.replace('\n', '')






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073081%2freplace-method-not-working-within-function%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      The issue with your current text replacement is that is considered an escape character- the literal characters n are interpreted as a newline character instead. To solution to this is to escape the character itself, via \. Your updated replace statement would then read:



      a = message.replace('\n', '')


      instead of:



      a = message.replace('n', '')





      share|improve this answer



























        1














        The issue with your current text replacement is that is considered an escape character- the literal characters n are interpreted as a newline character instead. To solution to this is to escape the character itself, via \. Your updated replace statement would then read:



        a = message.replace('\n', '')


        instead of:



        a = message.replace('n', '')





        share|improve this answer

























          1












          1








          1







          The issue with your current text replacement is that is considered an escape character- the literal characters n are interpreted as a newline character instead. To solution to this is to escape the character itself, via \. Your updated replace statement would then read:



          a = message.replace('\n', '')


          instead of:



          a = message.replace('n', '')





          share|improve this answer













          The issue with your current text replacement is that is considered an escape character- the literal characters n are interpreted as a newline character instead. To solution to this is to escape the character itself, via \. Your updated replace statement would then read:



          a = message.replace('\n', '')


          instead of:



          a = message.replace('n', '')






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 9 at 1:48









          Dillon DavisDillon Davis

          3,1732827




          3,1732827























              1














              This might be case that python or some other programming languages reads new line as 'n' escape character. So when python reads your file 'n' means new line and '\n' means actual 'n' character you wrote in the text file.



              So you need to replace like
              a = message.replace('\n', '')






              share|improve this answer



























                1














                This might be case that python or some other programming languages reads new line as 'n' escape character. So when python reads your file 'n' means new line and '\n' means actual 'n' character you wrote in the text file.



                So you need to replace like
                a = message.replace('\n', '')






                share|improve this answer

























                  1












                  1








                  1







                  This might be case that python or some other programming languages reads new line as 'n' escape character. So when python reads your file 'n' means new line and '\n' means actual 'n' character you wrote in the text file.



                  So you need to replace like
                  a = message.replace('\n', '')






                  share|improve this answer













                  This might be case that python or some other programming languages reads new line as 'n' escape character. So when python reads your file 'n' means new line and '\n' means actual 'n' character you wrote in the text file.



                  So you need to replace like
                  a = message.replace('\n', '')







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 9 at 1:42









                  xillarxillar

                  462




                  462



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073081%2freplace-method-not-working-within-function%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page