How do I remove items from a for loop? - python

So I'm trying to make a guessing game where you guess the name of a song using the first letter of each word, I've got the first word down but the next ones always display an extra '_' Can anyone help?
import random
import re
sWord = 0
correct = 0
lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
re.split(r"-", song)
sLists = (song.split("-"))
sList = sLists[0]
sLetter = sLists[0][0]
sWords = sList.split(" ")
sWordAmount = len(sWords)
sOutput = ("")
sGeneration = sList[1:]
for char in sGeneration:
if char == " ":
sOutput = sOutput + (" /")
elif char == "'":
sOutput = sOutput + (" '")
elif char == ".":
sOutput = sOutput + (" .")
elif char == ",":
sOutput = sOutput + (" ,")
elif char == "(":
sOutput = sOutput + (" (")
elif char == ")":
sOutput = sOutput + (" )")
else:
for i in range (sWordAmount):
if char == sWords[i][0]:
sOutput = sOutput + char
else:
sOutput = sOutput + (" _")
print (sLetter + sOutput + " By " + sLists[1])
If you need any more info please just ask!

This can be simplified with isalpha() to use an underscore in place of a letter otherwise keep the punctuation.
lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
name, artist = song.split('-')
s = ''
for word in name.split():
s += word[0] + ' '.join('_' if l.isalpha() else l for l in word[1:]) + ' /'
print(s[:-1] + ' By ' + artist)

What u are missing is a break in the for loop in your else branch.
for i in range(sWordAmount):
if char == sWords[i][0]:
sOutput = sOutput + char
break
else:
sOutput = sOutput + (" _")
Excerpt from Python Tips:
for loops also have an else clause which most of us are unfamiliar with. The else clause executes after the loop completes normally.
So the first letter of a new word inserted an additional _.

Related

Anagram program with sentences

I have a question about the following code:
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
"Race" and "Care" are now anagrams, but how to make an anagram with sentences?
For example:
str1 = "Race is good"
str2 = "Careisgood"
They are also an anagram, but it gives that it is not an anagram. I think it's because of the spaces. How to skip the spaces?
To remove spaces from a string, you can use the replace(" ", "") method.
str1 = "Race is good"
str2 = "Careisgood"
# convert both the strings into lowercase
str1 = str1.lower().replace(" ", "")
str2 = str2.lower().replace(" ", "")
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")

Replace all spaces in a string with underscores

How would I replace the spaces in a string with underscores without using the replace function. I was told to also use a accumulation string with some type of loop
string = input("Enter a string")
i = 0
acc = ""
for char in string:
if char == " ":
acc = string + "_"
print(acc)
Try this,
string = input("Enter a string")
i = 0
acc = ""
newlist = [] #create a new list which will be the output
strlist = list(string) #create a list of each character in the input string
for char in strlist:
if char == " ":
newlist.append('_')
newlist.append(char)
acc = ''.join(newlist)
print(acc)
Your code should to be :
string = input("Enter a string")
i = 0
acc = ""
for char in string:
if char == " ":
acc += "_"
else:
acc += char
print(acc)
Try it if without replace.
string = input("Enter a string")
res = ''.join(["_" if i == " " else i for i in string])
print(res)
Another method:
string = input("Enter a string")
res = "_".join(string.split(" "))
print(res)
Your code isn't too far off. You can use an accumulation string like this:
string = input("Enter a string")
acc = ""
for char in string:
if char == " ":
char = "_"
acc += char
print(acc)
If you are allowed to use split, then
s = 'Your string with spaces'
s_ = ''
for word in s.split():
s_ += '_' + word
s_[1:] # 'Your_string_with_spaces'
Otherwise, instead of words, concatenate characters with '_' instead of ' ':
s_ = ''
for char in s:
if char == ' ':
s_ += '_'
else:
s_ += char

Different methods to create exceptions to capitalizing a string

Is there another to have exception for capitalizing an entire sentence. I've heard of skipList method, but it didn't work for my code. See below:
string = input('Enter a string: ')
i = 0
tempString = ' '.join(s[0].upper() + s[1:] for s in string.split(' '))
result = ""
for word in tempString.split():
if i == 0:
result = result + word + " "
elif (len(word) <= 2):
result = result + word.lower() + " "
elif (word == "And" or word == "The" or word == "Not"):
result = result + word.lower() + " "
else:
result = result + word + " "
i = i + 1
print ("\n")
print (result)
Sure. Write a complete list of words that should not be title-cased ("and", "the", "or", "not", etc), and title-case everything else.
words = s.split(' ')
result = ' '.join([words[0]] + [w.title() for w in words[1:] if w not in skipwords])
of course this will still miss Mr. Not's last name, which should be capitalized, and some stranger things like "McFinnigan" will be wrong, but language is hard. If you want better than that, you'll probably have to look into NTLK.
You could rewrite this like this
skip_words = {w.capitalize(): w for w in 'a in of or to and for the'.split()}
words = string.title().split()
result = ' '.join(skip_words.get(w, w) for w in words).capitalize()

Looping through a string and only returning certain characters. Python

I have a problem when creating a function that's supposed to first return lowercase letters, "_" and "." and then uppercase letters, " " and "|" in that order. My version seems to return numbers and special characters like <># too which I don't want it to do, It's only supposed to read through the input string once and I don't know if that's achieved with my code.
My code is:
def split_iterative(n):
splitted_first = ""
splitted_second = ""
for i in n:
if i == i.lower() or i == "_" or i == ".":
splitted_first = splitted_first + i
elif i == i.upper() or i == " " or i == "|":
splitted_second = splitted_second + i
return splitted_first + splitted_second
if I do split_iterative("'lMiED)teD5E,_hLAe;Nm,0#Dli&Eg ,#4aI?rN#T§&e7#4E #<(S0A?<)NT8<0'")) it returns "'li)te5,_he;m,0#li&g ,#4a?r#§&e7#4 #<(0?<)8<0'MEDDELANDEINTESANT" which is incorrect as it should eliminate all those special characters and numbers. How do I fix this? It should return ('lite_hemligare', 'MEDDELANDE INTE SANT')
You could try this:
def f(input_string):
str1 = str2 = ""
for character in input_string:
if character.isalpha():
if character.islower():
str1 += character
else:
str2 += character
elif character in "_.":
str1 += character
elif character in " |":
str2 += character
return str1, str2
Output:
>>> input_string = "'lMiED)teD5E,_hLAe;Nm,0#Dli&Eg ,#4aI?rN#T§&e7#4E #<(S0A?<)NT8<0'"
>>>
>>> print f(input_string)
('lite_hemligare', 'MEDDELANDE INTE SANT')
>>>
This is because you are iterating through a string. The lowercase of the special characters is the same as the character. i.e.. '#'.lower() == '#'. hence it'll return '#' and all other special characters. you should explicitly check for alphabets using the isalpha() method on strings.
(i.isalpha() and i.lower() == i) or i == '_' or i == '.'
First, to make it return a list don't return the concatenated string but a list
Second, you are not checking or filtering out the characters, one way would be by checking if the character is a letter using isalpha() method
something like this:
def split_iterative(n):
splitted_first = ""
splitted_second = ""
for i in n:
if (i.isalpha() and i == i.lower()) or i == "_" or i == ".":
splitted_first = splitted_first + i
elif (i.isalpha() and i == i.upper()) or i == " " or i == "|":
splitted_second = splitted_second + i
#returns a list you can make it a variable if you need
return [splitted_first, splitted_second]
You can use ASCII values for the filtering of characters:
def split_iterative(n):
splitted_first = ""
splitted_second = ""
for i in n:
if ord(i) in range(97,122) or i == "_" or i == ".":
splitted_first = splitted_first + i
elif ord(i) in range(65,90) or i == " " or i == "|":
splitted_second = splitted_second + i
return (splitted_first , splitted_second)
You can make use of two lists while walking through characters of your text.
You can append lowercase, underscore, and stop characters to one list then uppercase, space and pipe characters to the other.
Finally return a tuple of each list joined as strings.
def splittext(txt):
slug, uppercase_letters = [], []
slug_symbols = {'_', '.'}
uppercase_symbols = {' ', '|'}
for letter in txt:
if letter.islower() or letter in slug_symbols:
slug.append(letter)
if letter.isupper() or letter in uppercase_symbols:
uppercase_letters.append(letter)
return ''.join(slug), ''.join(uppercase_letters)
txt="'lMiED)teD5E,_hLAe;Nm,0#Dli&Eg ,#4aI?rN#T§&e7#4E #<(S0A?<)NT8<0'"
assert splittext(txt) == ("lite_hemligare", "MEDDELANDE INTE SANT")

Python - Remove white space using only loops

I want to remove extra spaces in a string using only for/while loops, and if statements; NO split/replace/join.
like this:
mystring = 'Here is some text I wrote '
while ' ' in mystring:
mystring = mystring.replace(' ', ' ')
print(mystring)
output:
Here is some text I wrote
Here's what I tried. Unfortunately, it doesn't quite work.
def cleanupstring(S):
lasti = ""
result = ""
for i in S:
if lasti == " " and i == " ":
i = ""
lasti = i
result += i
print(result)
cleanupstring("Hello my name is joe")
output:
Hello my name is joe
My attempt doesn't remove all the extra spaces.
Change your code to this:
for i in S:
if lasti == " " and i == " ":
i = ""
else:
lasti = i
result += i
print(result)
Check that the current character and the next one are spaces, and if not, add them to a clean string. There really is no need for an and in this case, since we are comparing to the same value
def cleanWhiteSpaces(str):
clean = ""
for i in range(len(str)):
if not str[i]==" "==str[i-1]:
clean += str[i]
return clean
Uses the end of result in place of lasti:
def cleanupstring(S):
result = S[0]
for i in S[1:]:
if not (result[-1] == " " and i == " "):
result += i
print(result)
cleanupstring("Hello my name is joe")
Just try this
t = "Hello my name is joe"
" ".join(t.split())
this will output
"Hello my name is joe"

Categories