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

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived