Hi does anyone know how to make a function that replaces every alphabetic character in a string with a character from a given word (repeated indefinitely). If a character is not alphabetic it should stay where it is. Also this has to be done without importing anything.
def replace_string(string,word)
'''
>>>replace_string('my name is','abc')
'ab cabc ab'
So far i come up with:
def replace_string(string,word):
new=''
for i in string:
if i.isalpha():
new=new+word
else: new=new+i
print(new)
but, this function just prints 'abcabc abcabcabcabc abcabc' instead of 'ab cabc ab'
Change as follows:
def replace(string, word):
new, pos = '', 0
for c in string:
if c.isalpha():
new += word[pos%len(word)] # rotate through replacement string
pos += 1 # increment position in current word
else:
new += c
pos = 0 # reset position in current word
return new
>>> replace('my name is greg', 'hi')
'hi hihi hi hihi'
If you can't use the itertools module, first create a generator function that will cycle through your replacement word indefinitely:
def cycle(string):
while True:
for c in string:
yield c
Then, adjust your existing function just a little bit:
def replace_string(string,word):
new=''
repl = cycle(word)
for i in string:
if i.isalpha():
new = new + next(repl)
else:
new = new+i
return new
Output:
>>> replace_string("Hello, I'm Greg, are you ok?", "hi")
"hihih, i'h ihih, ihi hih ih?"
Another way to write this (but I think the first version is more readable and therefore better):
def replace_string(string,word):
return ''.join(next(cycle(word)) if c.isalpha() else c for c in string)
Related
we get a string from user and want to lowercase it and remove vowels and add a '.' before each letter of it. for example we get 'aBAcAba' and change it to '.b.c.b' . two early things are done but i want some help with third one.
str = input()
str=str.lower()
for i in range(0,len(str)):
str=str.replace('a','')
str=str.replace('e','')
str=str.replace('o','')
str=str.replace('i','')
str=str.replace('u','')
print(str)
for j in range(0,len(str)):
str=str.replace(str[j],('.'+str[j]))
print(str)
A few things:
You should avoid the variable name str because this is used by a builtin, so I've changed it to st
In the first part, no loop is necessary; replace will replace all occurrences of a substring
For the last part, it is probably easiest to loop through the string and build up a new string. Limiting this answer to basic syntax, a simple for loop will work.
st = input()
st=st.lower()
st=st.replace('a','')
st=st.replace('e','')
st=st.replace('o','')
st=st.replace('i','')
st=st.replace('u','')
print(st)
st_new = ''
for c in st:
st_new += '.' + c
print(st_new)
Another potential improvement: for the second part, you can also write a loop (instead of your five separate replace lines):
for c in 'aeiou':
st = st.replace(c, '')
Other possibilities using more advanced techniques:
For the second part, a regular expression could be used:
st = re.sub('[aeiou]', '', st)
For the third part, a generator expression could be used:
st_new = ''.join(f'.{c}' for c in st)
You can use str.join() to place some character in between all the existing characters, and then you can use string concatenation to place it again at the end:
# st = 'bcb'
st = '.' + '.'.join(st)
# '.b.c.b'
As a sidenote, please don't use str as a variable name. It's the name of the "string" datatype, and if you make a variable named it then you can't properly work with other strings any more. string, st, s, etc. are fine, as they're not the reserved keyword str.
z = "aBAcAba"
z = z.lower()
newstring = ''
for i in z:
if not i in 'aeiou':
newstring+='.'
newstring+=i
print(newstring)
Here I have gone step by step, first converting the string to lowercase, then checking if the word is not vowel, then add a dot to our final string then add the word to our final string.
You could try splitting the string into an array and then build a new string with the indexes of the array appending an "."
not too efficient but will work.
thanks to all of you especially allani. the bellow code worked.
st = input()
st=st.lower()
st=st.replace('a','')
st=st.replace('e','')
st=st.replace('o','')
st=st.replace('i','')
st=st.replace('u','')
print(st)
st_new = ''
for c in st:
st_new += '.' + c
print(st_new)
This does everything.
import re
data = 'KujhKyjiubBMNBHJGJhbvgqsauijuetystareFGcvb'
matches = re.compile('[^aeiou]', re.I).finditer(data)
final = f".{'.'.join([m.group().lower() for m in matches])}"
print(final)
#.k.j.h.k.y.j.b.b.m.n.b.h.j.g.j.h.b.v.g.q.s.j.t.y.s.t.r.f.g.c.v.b
s = input()
s = s.lower()
for i in s:
for x in ['a','e','i','o','u']:
if i == x:
s = s.replace(i,'')
new_s = ''
for i in s:
new_s += '.'+ i
print(new_s)
def add_dots(n):
return ".".join(n)
print(add_dots("test"))
def remove_dots(a):
return a.replace(".", "")
print(remove_dots("t.e.s.t"))
I'm having difficulty with the isspace function. Any idea why my code is wrong and how to fix it?
Here is the problem:
Implement the get_num_of_non_WS_characters() function. get_num_of_non_WS_characters() has a string parameter and returns the number of characters in the string, excluding all whitespace.
Here is my code:
def get_num_of_non_WS_characters(s):
count = 0
for char in s:
if char.isspace():
count = count + 1
return count
You want non whitespace, so you should use not
def get_num_of_non_WS_characters(s):
count = 0
for char in s:
if not char.isspace():
count += 1
return count
>>> get_num_of_non_WS_characters('hello')
5
>>> get_num_of_non_WS_characters('hello ')
5
For completeness, this could be done more succinctly using a generator expression
def get_num_of_non_WS_characters(s):
return sum(1 for char in s if not char.isspace())
A shorter version of #CoryKramer answer:
def get_num_of_non_WS_characters(s):
return sum(not c.isspace() for c in s)
As an alternative you could also simple do:
def get_num_of_non_WS_characters(s):
return len(''.join(s.split()))
Then
s = 'i am a string'
get_num_of_non_WS_characters(s)
will return 10
This will also remove tabs and new line characters:
s = 'i am a string\nwith line break'
''.join(s.split())
will give
'iamastringwithlinebreak'
I would just use n=s.replace(" " , "") and then len(n).
Otherwise I think you should increase the count after the if statement and put a continue inside it.
I am trying to figure out how to at least start this. It is in python.
def countChars(inString):
sentence = raw_input()
while a in sentence:
sentence.append[]
Something along the lines of this should work:
def count_chars(str):
letters = dict()
for c in iter(str):
letters.setdefault(c, 0)
letters[c] += 1
print(letters.items())
I'm trying to write a function that returns a string with every xth character followed by an asterisk.
string_chunks("once upon a time, in a land far far away, 5)
should return:
'O*once u*pon a* time*, in a lan*d far far* away*'
Here is my code so far:
def string_chunk(string, x):
strings = ""
y = x
for char in string:
strings += string[y-x:y] + "*"
y += x
return strings
print string_chunk("summer is really cool", 5)
This is what I get. I dont want the added asterisks at the end.
"summe*r is *reall*y coo*l*****************"
You could use a list comprehension and then join tha list with an asterisk:
astr = 'this is an example string'
'*'.join([astr[j*5:j*5+5] for j in xrange(len(astr)/5+1)])
## 'this *is an* exam*ple s*tring*'
astr = 'this is an example string too'
'*'.join([astr[j*5:j*5+5] for j in xrange(len(astr)/5+1)])
## 'this *is an* exam*ple s*tring* too'
I need to create a function that counts the frequency of an inputed letter in a piece of text...
e.g.
import urllib
pieceoftext =urllib.urlopen(blahblahblah).read()
def frequency(char):
count = 0
for character in pieceoftext:
count += 1
return count
...
Any help would be appreciated :)
def frequency(char, sentence):
count = 0
for k in list(sentence):
if k == char:
count+=1
return count
This runs as:
frequency('t', 'the quick brown fox jumps over the lazy dog.')
2
list(sentence) gets each individual character in the sentence, which we loop over with a for loop. We then check if the character is the one specified, and if it is, we add one to our variable count. At the end, we return count.
As #Hamatti said below, you do not need to convert to a list first, so here is a simplified version of the code:
def frequency(char, sentence):
count = 0
for k in sentence:
if k.lower() == char.lower():
count+=1
return count
EDIT:
If the sentence is imported as a piece of text from a url, use the following code:
sentence = urllib.urlopen('myamazingurl.com').read()
def frequency(char, sentence):
count = 0
for k in sentence:
if k.lower() == char.lower():
count+=1
return count
Then continue as needed. All this does is assigns the variable sentence to the text in the url. You can also assign sentence within the frequency function, if you will always be pulling from the same url. For that, use the following code:
def frequency(char):
count = 0
sentence = urllib.urlopen('myamazingurl.com').read()
for k in sentence:
if k.lower() == char.lower():
count+=1
return count
You can alter this if you don't want two parameters, but it's probably better to use two in this case.
def frequency(c, sentence):
count = 0
for character in sentence:
if (c.lower() == character.lower()):
count += 1
return count
>>> frequency('c', 'ccc')
>>> 3
Note that I used the lower() method to make the comparison case-insensitive.
You can use Counter in the collections module.
import collections
def frequency(char, string):
string = string.lower()
count = collections.Counter(string)
return count[char]
Ideally, string = string.lower() should be omitted and you should pass the string already lower-cased if you wish.
pieceoftext.lower().count('t')
or
frequency = lambda c, s=pieceoftext: s.lower().count(c)
frequency('t') # returns 2
frequency('t', pieceoftext) # returns 2
frequency('t', 'tttt') # returns 4
def frequency(c,sentance):
return sum([c==ch for ch in sentance])
is how I would do it ... if I wasnt going to use count anyway