I am parsing a string for spaces and i find that the string index is not getting updated even after updating the string, where am i wrong ? will be very happy for any guidance provided
class Palindrome:
def __init__(self,seq):
self.seq=seq.lower()
def remove_space(self):
print('up',self.seq)
for num,i in enumerate(self.seq):
print('start',self.seq)
if i==' ':
print('orig',(num,i))
new_seq=self.seq[:num]+self.seq[num+1:]
num=num+1
self.seq=new_seq # updating the string here
print('now',self.seq)
print(num)
#print(new_seq)
seq1=Palindrome('superman is here')
seq1.remove_space() ```
If you want to proceed with your method, you need to account for the number of spaces you've already removed from the string. And I also included an alternative way of removing space while still using a loop.
class Palindrome:
def __init__(self,seq):
self.seq=seq.lower()
def remove_space_alt(self):
print(self.seq)
temp_string = ''
for i, letter in enumerate(self.seq):
if letter != ' ':
temp_string += letter
self.seq = temp_string
print(self.seq)
def remove_space(self):
print(self.seq)
space_count = 0
for i, letter in enumerate(self.seq):
if letter == ' ':
first = self.seq[:i - space_count]
second = self.seq[i + 1 - space_count:]
space_count += 1
self.seq = first + second
print(self.seq)
print('Showing remove_space')
seq1=Palindrome('superman is here')
seq1.remove_space()
print('\nShowing remove_space_alt')
seq1=Palindrome('superman is here')
seq1.remove_space_alt()
Output:
Showing remove_space
superman is here
supermanis here
supermanishere
Showing remove_space_alt
superman is here
supermanishere
Original Post: Suggested using string replace() to remove spaces, and did not fully explain issue with changing for-loop index mid loop.
Related
I am very new to programming, so sorry for a basic question. I am trying to write a function that will take a string in which words are divided by ',' and return a list of these words (the Split method). My code is:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list + ['']
return my_shop_list
print(str_to_list("Milk,Cottage,Tomatoes")) should look like [Milk, Cottage, Tomatoes]
but I am keep getting IndexError: list index out of range.
I read some answers here and couldn't find something to work.
Can anyone explain what is wrong.
list has the method append so a solution will be something like this:
def str_to_list(my_shop_str):
my_shop_list = ['']
word_in_list = 0
for letter in my_shop_str:
if letter != ',':
my_shop_list[word_in_list] += letter
else:
word_in_list += 1
my_shop_list.append('')
return my_shop_list
PS: Do not forgot about empty spaces between words in string like "aaa, bbb, ccc" will be ['aaa', ' bbb', ' ccc'] with spaces.
def sp(s):
l =[]
while True:
comma = s.find(',')
if comma == -1:
l.append(s)
break
l.append(s[:comma])
s = s[comma+1:]
print(l)
this is a simplified version hope it helps.
Simplest Way:
We can use an inbuilt split function.
def Convert(string):
# split the string whenever "," occurs
# store the splitted parts in a list
li = list(string.split(","))
return li
# Driver code
str1 = "Hello,World"
print(Convert(str1))
Output:
["Hello", "World"]
I am a beginner to python, and I was tasked with creating a function that accepts a string as the parameter and return the number of words in the string.
I am having trouble with the spaces and the blank string I assigned. I feel like I am missing something, but am a bit lost as to what's missing or what I've messed up. Also we can't use split.
Any guidance or help would be greatly appreciated
This is what I have so far:
def word_count(str):
count = 1
for i in str:
if (i == ' '):
count += 1
print (count)
word_count('hello') --> Output = 1 (so far correct)
word_count('how are you?') --> Output = 3 (also correct/at least what i am looking for)
word_count(' this string has wide spaces ') --> Output = 7 (Should be 5...)
word_count(' ') --> Output = 2 (Should be ''. I think it's doing count(1+1))
use this code as an improvement
def word_count(str):
count = 1
for i in str:
if (i == ' '):
count += 1
if str[0] == ' ':
count -= 1
if str[-1] == ' ':
count -= 1
print (count)
your error is because your counting spaces if they start at beginning or appear at end.
NOTE that you can't pass empty string "" since this is evaluated to NONE, and trying to index it will cause an error
The problem seems to be when there is a blank in front or behind the sentence. A way to fix this is by using a built in function 'strip'. For example, we can do the following:
example_string = " This is a string "
print(example_string)
stripped_string = example_string.strip()
print(stripped_string)
The output of the first string will be
" This is a string "
The output of the second string will be
"This is a string"
What you can do is the following:
def word_count(input_str):
return len(input_str.split())
count = word_count(' this is a test ')
print (count)
It basically removes the leading/trailing spaces and splits the phrase into
a list.
If, on the offchance you need to use a loop:
def word_count(input_str):
count = 0
input_str = input_str.strip()
for i in input_str:
if (i == ' '):
count += 1
return count
count = word_count(' this is a test ')
print (count)
I'm working on an assignment and have gotten stuck on a particular task. I need to write two functions that do similar things. The first needs to correct capitalization at the beginning of a sentence, and count when this is done. I've tried the below code:
def fix_capitalization(usrStr):
count = 0
fixStr = usrStr.split('.')
for sentence in fixStr:
if sentence[0].islower():
sentence[0].upper()
count += 1
print('Number of letters capitalized: %d' % count)
print('Edited text: %s' % fixStr)
Bu receive an out of range error. I'm getting an "Index out of range error" and am not sure why. Should't sentence[0] simply reference the first character in that particular string in the list?
I also need to replace certain characters with others, as shown below:
def replace_punctuation(usrStr):
s = list(usrStr)
exclamationCount = 0
semicolonCount = 0
for sentence in s:
for i in sentence:
if i == '!':
sentence[i] = '.'
exclamationCount += 1
if i == ';':
sentence[i] = ','
semicolonCount += 1
newStr = ''.join(s)
print(newStr)
print(semicolonCount)
print(exclamationCount)
But I'm struggling to figure out how to actually do the replacing once the character is found. Where am I going wrong here?
Thank you in advance for any help!
I would use str.capitalize over str.upper on one character. It also works correctly on empty strings. The other major improvement would be to use enumerate to also track the index as you iterate over the list:
def fix_capitalization(s):
sentences = [sentence.strip() for sentence in s.split('.')]
count = 0
for index, sentence in enumerate(sentences):
capitalized = sentence.capitalize()
if capitalized != sentence:
count += 1
sentences[index] = capitalized
result = '. '.join(sentences)
return result, count
You can take a similar approach to replacing punctuation:
replacements = {'!': '.', ';': ','}
def replace_punctuation(s):
l = list(s)
counts = dict.fromkeys(replacements, 0)
for index, item in enumerate(l):
if item in replacements:
l[index] = replacements[item]
counts[item] += 1
print("Replacement counts:")
for k, v in counts.items():
print("{} {:>5}".format(k, v))
return ''.join(l)
There are better ways to do these things but I'll try to change your code minimally so you will learn something.
The first function's issue is that when you split the sentence like "Hello." there will be two sentences in your fixStr list that the last one is an empty string; so the first index of an empty string is out of range. fix it by doing this.
def fix_capitalization(usrStr):
count = 0
fixStr = usrStr.split('.')
for sentence in fixStr:
# changed line
if sentence != "":
sentence[0].upper()
count += 1
print('Number of letters capitalized: %d' % count)
print('Edited text: %s' % fixStr)
In second snippet you are trying to write, when you pass a string to list() you get a list of characters of that string. So all you need to do is to iterate over the elements of the list and replace them and after that get string from the list.
def replace_punctuation(usrStr):
newStr = ""
s = list(usrStr)
exclamationCount = 0
semicolonCount = 0
for c in s:
if c == '!':
c = '.'
exclamationCount += 1
if c == ';':
c = ','
semicolonCount += 1
newStr = newStr + c
print(newStr)
print(semicolonCount)
print(exclamationCount)
Hope I helped!
Python has a nice build in function for this
for str in list:
new_str = str.replace('!', '.').replace(';', ',')
You can write a oneliner to get a new list
new_list = [str.replace('!', '.').replace(';', ',') for str in list]
You also could go for the split/join method
new_str = '.'.join(str.split('!'))
new_str = ','.join(str.split(';'))
To count capitalized letters you could do
result = len([cap for cap in str if str(cap).isupper()])
And to capitalize them words just use the
str.capitalize()
Hope this works out for you
This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)
You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'
Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))
Try to append it in a temporary string and to print it at the end ;)
print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))
I have to do this exercise without using library function. So far I have reached here:-
string = input("Enther The String :")
substring = input("Enter the substring :")
count = 0
for i in range(len(string)):
if string[i:i+len(substring)] == substring:
if string[i+len(substring)] == ' ':
count += 1
else:
count = 0
print(count)
But, let us say if the sub-string is 'bob' and the string is 'bob cat bob cat bobs cat', the program still counts 'bob' in 'bobs' and I don't want that. Also this code always returns 0. Please help! Thanks!
the program still counts 'bob' in 'bobs'
It doesn't.
Also this code always returns 0
This is because of your else clause.
else:
count = 0
You're resetting the count here. That's not what you want; if the next character isn't a space, you don't want to do anything at all. Remove the whole else clause.
You have an additional bug you haven't noticed. If string ends with substring, the following test:
if string[i+len(substring)] == ' ':
will attempt to read past the end of the string and throw an IndexError. Try to solve this problem on your own first.
As you're allowed to use slicing, so you can use that to check whether the character before/after the substring is a space or empty string, if it is then increment count by 1. Note that slices never raise exception, even for out of range indices.
def sub_str_count(s, sub_str):
le = len(sub_str)
count = 0
for i in range(len(s)):
if s[i:i+le] == sub_str and s[i-1:i] in ('', ' ') and \
s[i+le:i+le+1] in ('', ' '):
count += 1
return count
Exception handling based version of the above code:
def check(s, ind):
"""
Check whether the item present at this index is a space or not.
For out of bound indices return True.
For negative indices return True.
"""
if ind < 0:
return True
try:
return s[ind] == ' '
except IndexError:
return True
def sub_str_count(s, sub_str):
le = len(sub_str)
count = 0
for i in range(len(s)):
if s[i:i+le] == sub_str and check(s, i-1) and check(s, i+le):
count += 1
return count