Python Forum
Replacing all letters in a string apart from the first letter in each word
Thread Rating:
  • 4 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replacing all letters in a string apart from the first letter in each word
#1
Hey,
I am coding a song guessing game and at the moment i have succeeded. But i have a problem. When the code starts and allows the user to guess the song, it shows the user what the full name of the song is.
For example:
def main():
    playerScore=0
    guessCounter = 0
    # This is where you can change the max turns and guesses
    maxTurns=999999999
    maxGuesses = 2
    while True:
        randNum = int(random.randint(0, 19))
        f=open('Songs.txt')
        linesa=f.read().splitlines()
        g=open('Artists.txt')
        linesb=g.read().splitlines()

        for turnCounter in range(maxTurns):
            randNum = int(random.randint(0, 19))
            f=open('Songs.txt')
            linesa=f.read().splitlines()
            g=open('Artists.txt')
            linesb=g.read().splitlines()

            # Pick a random song:
            print('==============================================')
            randsong =(linesa[randNum])
            randart =(linesb[randNum])
            print(randsong)
            print(randart)
            print('==============================================')
            # Prompt for a guess:
            songGuess = input("What is the song called?\n==============================================\n>> ")
This code would output a random song from a text file but it would out put it like this:

==============================================
Ruin My Life
by Zara Larsson
==============================================
What is the song called?
==============================================
but i would like it to look like this:

==============================================
R___ M_ L___
by Zara Larsson
==============================================
What is the song called?
==============================================

How do i do this exactly? Wall Wall Wall


(If you need the full code then here is the pastebin link: https://pastebin.com/6mzLnfaK)
Reply
#2
I observe that you open files many times and never close them. Beside that, why don't you read file content into data structure and work with that?

Regarding question how to get first letter and underscores from string, one way of doing it:

>>> def obscure(song_name):
...     return ' '.join([f'{word[0]}{(len(word) - 1) * " _ "}' for word in song_name.split()])
...
>>> song = 'Ruin My Life'
>>> print(obscure(song))
R _  _  _  M _  L _  _  _
I added empty spaces around underscores for better visibility.

If list comprehension seems complicated then in plain English: give me a string which consists first letter of word and number of underscores corresponding to length of word minus one for every word in song name (this code uses f-strings, but it can be easily done with .format method)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
perfringo,
I am not sure how to do that as i am sorta new to python, how would i implement that into my code?
And also how would i "Read file content into data structure"?
I know how to close files but i just didn't see the need of doing it at the time as i will be constantly reading from them.

perfingo,
The code
def obscure(song_name):
    return ' '.join([f'{word[0]}{(len(word) - 1) * " _ "}' for word in song_name.split()])
didnt work...
Invalid syntax
Reply
#4
(Jan-14-2019, 09:44 AM)Carbonix Wrote: I am not sure how to do that as i am sorta new to python, how would i implement that into my code?
And also how would i "Read file content into data structure"?
I know how to close files but i just didn't see the need of doing it at the time as i will be constantly reading from them.

You should define the function before you use it (before calling main()). Then on row 25 of your initial code modify print(randsong) to print(obscure(randsong))

There in no point of opening file several times. Especially when you don't close it (quote from unknown source: "not closing a file is a sin and you deserve all bad things which will happen to you as result of that"). Some things what can happen are described in answers to question in Quora and StackOverflow. Usually you open file, grab needed data in suitable format/structure and work with that data (not repeatedly open files without closing them). Good practice is to open files something like this: with open('spam.csv', 'r', encoding='UTF-8') as f:. In this case Python automatically closes file for you.

NB! In order to use f-strings you should have Python version 3.6 or later.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
Okay i got that part but im on about the actual code that you gave me
    return ' '.join([f'{word[0]}{(len(word) - 1) * " _ "}' for word in song_name.split()])
does not work, it has an invalid syntax.
and also when i run the code with this
    return ' '.join([f(word[0])((len(word) - 1) * " _ ") for word in song_name.split()])
(which hasn't got the curly brackets and is missing some speech marks)
i get:

Traceback (most recent call last):
File "N:\Yee\A\Py\SongGame - Copy.py", line 146, in <module>
unimportant()
File "N:\Yee\A\Py\SongGame - Copy.py", line 17, in unimportant
mainMenu()
File "N:\Yee\A\Py\SongGame - Copy.py", line 40, in mainMenu
main()
File "N:\Yee\A\Py\SongGame - Copy.py", line 74, in main
print(obscure(randsong))
File "N:\Yee\A\Py\SongGame - Copy.py", line 50, in obscure
return ' '.join([f(word[0])((len(word) - 1) * " _ ") for word in song_name.split()])
File "N:\Yee\A\Py\SongGame - Copy.py", line 50, in <listcomp>
return ' '.join([f(word[0])((len(word) - 1) * " _ ") for word in song_name.split()])
TypeError: '_io.TextIOWrapper' object is not callable


Any chance you could put it into example in my full code? full code is here https://pastebin.com/6mzLnfaK
(I am running python ver 3.4.1)
Reply
#6
(Jan-17-2019, 08:50 AM)Carbonix Wrote: Okay i got that part but im on about the actual code that you gave me
Python Code: (Double-click to select all)

return ' '.join([f'{word[0]}{(len(word) - 1) * " _ "}' for word in song_name.split()])
does not work, it has an invalid syntax.

Nope, it works. If you get error then you have something different

def test(song_name):
    return ' '.join([f'{word[0]}{(len(word) - 1) * " _ "}' for word in song_name.split()])

print(test("Nothing Else Matters"))
Output:
N _ _ _ _ _ _ E _ _ _ M _ _ _ _ _ _ >>>
Post your actual code and full traceback you get.


As to the other line you tried - it's really incorrect syntax.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Do i have to be on a specific version of python for this to work because i literally pasted the code you put in into a new python doc and im still getting the error, do i need to import anything?
def test(song_name):
    return ' '.join([f--------->'{word[0]}{(len(word) - 1) * " _ "}'<--------- for word in song_name.split()])
 
print(test("Nothing Else Matters"))
Where i have put the arrows is where the error is happening
Reply
#8
Because of using f-strings it will work for 3.6+
in a version before 3.6 you need to replace f-string with format

def test(song_name):
    return ' '.join(['{}{}'.format(word[0], (len(word) - 1) * " _ ") for word in song_name.split()])
 
print(test("Nothing Else Matters"))
this will work also for 3.6+, but f-strings faster and more readble
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
Well there we have it then, im on version 3.4.1
Thank you
It works now
Reply
#10
Aha, I thought you have seen this note in the perfingo's post:

(Jan-14-2019, 11:19 AM)perfringo Wrote: NB! In order to use f-strings you should have Python version 3.6 or later.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Retrieve word from string knob 4 432 Jan-22-2024, 06:40 PM
Last Post: Pedroski55
  extract substring from a string before a word !! evilcode1 3 491 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  Replacing String Variable with a new String Name kevv11 2 729 Jul-29-2023, 12:03 PM
Last Post: snippsat
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 796 Mar-21-2023, 03:43 AM
Last Post: mm309d
  Isolate a word from a long string nicocorico 2 1,501 Feb-25-2022, 01:12 PM
Last Post: nicocorico
  change string in MS word Mr_Blue 8 3,217 Sep-19-2021, 02:13 PM
Last Post: snippsat
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,455 Aug-12-2021, 04:25 PM
Last Post: palladium
  Trying to get the first letter of every word in a list DanielCook 2 2,101 Jan-05-2021, 05:06 PM
Last Post: deanhystad
  Replacing a words' letters in a string cananb 2 3,407 Dec-01-2020, 06:33 PM
Last Post: perfringo
  Trying to find first 2 letter word in a list of words Oldman45 7 3,627 Aug-11-2020, 08:59 AM
Last Post: Oldman45

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020