Python string replacement with the same number of '*'s - python

I'm trying to replace a given word in the string with the same number of '*'s and then print that new string. But it's not working
def censor(text , word):
l = len(word)
k = " " + str(word) + " "
if k in text:
text.replace(k , l*'*')
return text
print censor('this word duck and this word duck is censored', 'duck')

Strings are immutable. That means their methods don't change the object. If anything they return a new object. This is the case with str.replace. text.replace returns a modified string but you don't keep it, and text itself is not modified. You need to do this:
text = text.replace(k , l*'*')
I recommend reading the official Python tutorial.

Related

How can I use isalpha() to replace non-alphabetic characters with white spaces?

I'm trying to check and see if every character in a given string is alphabetic. If it isn't, then replace whatever the character is with a blank space. What I have so far is:
def removePunctuation(txt):
for char in txt:
if char.isalpha() == False:
txt.replace(char, " ")
return txt
I've tested some input but it's not removing anything.
The Python Way:
Use join() and a generator expression like:
new_txt = ''.join(c if c.isalpha() else ' ' for c in txt)
Why did my code not work?
The basic problem with your code is that in Python strings are immutable. Which is to say, once they are built, they never change. You can discard them because you are done with them, but you cannot change them. Because of this .replace() does not change txt. What is does do is return a new string with the characters replaced. This is not at all what you want in the loop you have constructed.
Using str.translate and a defaultdict is a good way to approach translation problems.
from collections import defaultdict
from string import ascii_letters
translation = defaultdict(lambda: ' ', str.maketrans(ascii_letters, ascii_letters))
print('Hello.World!'.translate(translation))
The minimum change required to make your function work is:
def removePunctuation(txt):
for char in txt:
if char.isalpha() == False:
txt = txt.replace(char, " ")
return txt
new_txt = removePunctuation(txt)
Strings are immutable, so str.replace does not alter its argument, but returns a new string.
However, Stephen Rauch's one-liner is a more "Python" way of accomplishing this.
def removePunctuation(txt):
return ''.join(c if c.isalpha() else ' ' for c in txt)
new_txt = removePunctuation(txt)

split strings with multiple special characters into lists without importing anything in python

i need to make a program that will capitalize the first word in a sentence and i want to be sure that all the special characters that are used to end a sentence can be used.
i can not import anything! this is for a class and i just want some examples to do this.
i have tried to use if to look in the list to see if it finds the matching character and do the correct split operatrion...
this is the function i have now... i know its not good at all as it just returns the original string...
def getSplit(userString):
userStringList = []
if "? " in userString:
userStringList=userString.split("? ")
elif "! " in userStringList:
userStringList = userString.split("! ")
elif ". " in userStringList:
userStringList = userString.split(". ")
else:
userStringList = userString
return userStringList
i want to be able to input something like this is a test. this is a test? this is definitely a test!
and get [this is a test.', 'this is a test?', 'this is definitely a test!']
and the this is going to send the list of sentences to another function to make the the first letter capitalized for each sentence.
this is an old homework assignment that i could only make it use one special character to separate the string into a list. buti want to user to be able to put in more then just one kind of sentence...
This may hep. use str.replace to replace special chars with space and the use str.split
Ex:
def getSplit(userString):
return userString.replace("!", " ").replace("?", " ").replace(".", " ").split()
print(map(lambda x:x.capitalize, getSplit("sdfsdf! sdfsdfdf? sdfsfdsf.sdfsdfsd!fdfgdfg?dsfdsfgf")))
Normally, you could use re.split(), but since you cannot import anything, the best option would be just to do a for loop. Here it is:
def getSplit(user_input):
n = len(user_input)
sentences =[]
previdx = 0
for i in range(n - 1):
if(user_input[i:i+2] in ['. ', '! ', '? ']):
sentences.append(user_input[previdx:i+2].capitalize())
previdx = i + 2
sentences.append(user_input[previdx:n].capitalize())
return "".join(sentences)
I would split the string at each white space. Then scan the list for words that contain the special character. If any is present, the next word is capitalised. Join the list back at the end. Of course, this assumes that there are no more than two consecutive spaces between words.
def capitalise(text):
words = text.split()
new_words = [words[0].capitalize()]
i = 1
while i < len(words) - 1:
new_words.append(words[i])
if "." in words[i] or "!" in words[i] or "?" in words[i]:
i += 1
new_words.append(words[i].capitalize())
i += 1
return " ".join(new_words)
If you can use the re module which is available by default in python, this is how you could do it:
import re
a = 'test this. and that, and maybe something else?even without space. or with multiple.\nor line breaks.'
print(re.sub(r'[.!?]\s*\w', lambda x: x.group(0).upper(), a))
Would lead to:
test this. And that, and maybe something else?Even without space. Or with multiple.\nOr line breaks.

Creating sentences by a function without using a package

Im currently writing a program that looks at a list and iterates through a groups the words into sentences but whenever i ran it, I got [] and im not 100% sure why. Here is my code for reading in the file, and creating the sentence and an attached snippet of the list.
def import_file(text_file):
wordcounts = []
with open(text_file, encoding = "utf-8") as f:
pride_text = f.read()
sentences = pride_text.split(" ")
return sentences
def create_sentance(sentance):
sentence_list=[]
my_sentence=""
for character in sentance:
if character=='.' or character=='?' or character=='!':
sentence_list.append(my_sentence)
my_sentence=""
else:
my_sentence=my_sentence + character
return sentence_list
Preview of List
Calling of my functions
pride=import_file("pride.txt")
pride=remove_abbreviations_and_punctuation(pride)
pride=create_sentance(pride)
print(pride)
Your return sentence_list is indented one further than it should be. After the first iteration of the for, should the else condition execute and not the if, then your function returns sentence_list which was initialized to [ ]. Either way, if sentence was 20 characters long, your for will only run once given where your return call is.
Make the following change:
def create_sentance(sentance):
sentence_list=[]
my_sentence=""
for character in sentance:
if character=='.' or character=='?' or character=='!':
sentence_list.append(my_sentence)
my_sentence=""
else:
# do you not want this in 'sentence_list'?
my_sentence=my_sentence + character
return sentence_list
The reason your function is returning an empty list is because your return is inside the for loop. In addition, "character" is actually a word, since each element of your list is a word. This program works:
def create_sentance(sentance):
sentence_list=[]
my_sentence=""
for character in sentance:
print character
if '.' in character or '?' in character or '!' in character:
sentence_list.append(my_sentence + ' ' + character)
my_sentence=""
else:
my_sentence=my_sentence + ' ' + character
return sentence_list
create_sentance(['I','will','go','to','the','park.','Ok?'])
You need to use "in" instead of == because each character is a word. Try printing "character" to see this. The above program works and returns the result
[' I will go to the park.', 'Ok?']
which is what you were intending.

Python 3 - How to capitalize first letter of every sentence when translating from morse code

I am trying to translate morse code into words and sentences and it all works fine... except for one thing. My entire output is lowercased and I want to be able to capitalize every first letter of every sentence.
This is my current code:
text = input()
if is_morse(text):
lst = text.split(" ")
text = ""
for e in lst:
text += TO_TEXT[e].lower()
print(text)
Each element in the split list is equal to a character (but in morse) NOT a WORD. 'TO_TEXT' is a dictionary. Does anyone have a easy solution to this? I am a beginner in programming and Python btw, so I might not understand some solutions...
Maintain a flag telling you whether or not this is the first letter of a new sentence. Use that to decide whether the letter should be upper-case.
text = input()
if is_morse(text):
lst = text.split(" ")
text = ""
first_letter = True
for e in lst:
if first_letter:
this_letter = TO_TEXT[e].upper()
else:
this_letter = TO_TEXT[e].lower()
# Period heralds a new sentence.
first_letter = this_letter == "."
text += this_letter
print(text)
From what is understandable from your code, I can say that you can use the title() function of python.
For a more stringent result, you can use the capwords() function importing the string class.
This is what you get from Python docs on capwords:
Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

How to split up a long list using \n

Here is a long string that I convert to a list so I can manipulate it, and then join it back together. I am having some trouble being able to have an iterator go through the list and when the iterator reach, let us say every 5th object, it should insert a '\n' right there. Here is an example:
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string = string.split()
# do the magic here
string = ' '.join(string)
print(string)
Output:
Hello my name is Josh
I like pizza and python
I need this string to
be really really long
Any idea how i can achieve this?
I tried using:
for words in string:
if words % 5 == 0:
string.append('\n')
but it doesn't work. What am I missing?
What you're doing wrong is attempting to change string in your example which doesn't affect the string contained in your list... instead you need to index into the list and directly change the element.
text = "Hello my name is Josh I like pizza and python I need this string to be really really long"
words = text.split()
for wordno in range(len(words)):
if wordno and wordno % 5 == 0:
words[wordno] += '\n'
print ' '.join(words)
You don't want to call something string as it's a builtin module that is sometimes used and may confuse things, and I've also checked that wordno isn't 0 else you'll end up with a single word line in your rejoin...
The problem with the for loop you attempted to use, is that it didn't keep the index of the word, and thus could not determine which word that was the 5th. By using enumerate(iterable) you can get the index of the word, and the word at the same time. You could also just use range(len(iterable)) to get the index and just do it the same way.
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string = string.split()
for word_num, word in enumerate(string):
if word_num and word_num % 5 == 0:
# access the array since changing only the variable word wont work
string[word_num] += '\n'
string = ' '.join(string)
print(string)
Edit:
As #JonClements pointed out, this causes "Hello" to be printed on its own line, because 0%5 = 0. Therefore I added a check to see if word_num evaluates to True (which it does if it is not equal to 0)
In this case you should probably be creating a new string instead of trying to modify the existing one. You can just use a counter to determine which word you're on. Here's a very simple solution, though Jon Clements has a more sophisticated (and probably more efficient) one:
newstring = ""
str = "Hello my name is Josh I like pizza and python I need this string to be really really long"
strlist = str.split()
for i, words in enumerate(strlist):
newstring += words
if (i + 1) % 5 == 0:
newstring += "\n"
else:
newstring += " "
`enumerate1 returns both the index of the word in your list of words, as well as the word itself. It's a handy automated counter to determine which word you're on.
Also, don't actually name your string string. That's the name of a module that you don't want to overwrite.
I am sure this could be much shorter but this does what you want. They key improvements are a new string to hold everything and the use of enumerate to catch the ith word in the list.
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string2 = ""
for (i,word) in enumerate(string.split()):
string2 = string2 + " " + word
if (i + 1) % 5 == 0:
string2 = string2 + '\n'
print(string2)
you can use enumerate() on your string after you split it.
and iterate like that:
new_string_list = []
for index, word in string:
if (index + 1) % 5 == 0:
word += '\n'
new_string_list.append(word)
string = ' '.join(new_string_list)
Use enumerate to get index and % operation on i to append '\n' every n blocks
new_string_list = []
strlist = oldstr.split()
// do magic here
for i,word in enumerate(strlist):
new_string_list.append(word) #it is better
#to append to list then join, using + to concatenate strings is ineffecient
if count % 5 == 0:
new_string_list.append('\n')
print("".join(new_string_list))
Using list slicing...
s='hello my name is josh i like pizza and python i need this string to be really really long'
l=s.split()
l[4::5]=[v+'\n' for v in l[4::5] ]
print '\n'.join(' '.join(l).split('\n '))
hello my name is josh
i like pizza and python
i need this string to
be really really long
Horrible one-liner I cooked up as an example of what you should never do.
s='hello my name is josh i like pizza and python i need this string to be really really long'
print '\n'.join([' '.join(l) for l in [s.split()[i:i + 4] for i in range(0, len(s.split()), 4)]])

Categories