#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    1
    Rep Power
    0

    Need help writing a loop


    I am trying to write a loop that will replace one word in a sentence without using .replace.

    Example: "This has been a long day"

    create a loop which replaces day with the word night and prints "This has been a long night"

    I am pretty new to Python and loops are difficult for me to grasp.

    Any help would be appreciated.

    Thank you.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2012
    Posts
    33
    Rep Power
    3
    while ’day’ in a_string:
    a_string = sub(’day', 'night', a_string)


    sorry this code is untested
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    606
    Rep Power
    65
    Could be something like this:
    Code:
    s1 = "This has been a long day"
    print(s1)
    print('-'*30)  # 30 dashes
    
    s2 = ""
    # splits sentence at white spaces
    for word in s1.split():
        print(word) # test
        if word == "day":
            word = "night"
        s2 += word + " "
    
    print('-'*30)  # 30 dashes
    print(s2)
    
    '''my result >>
    This has been a long day
    ------------------------------
    This
    has
    been
    a
    long
    day
    ------------------------------
    This has been a long night 
    '''
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo