How to extract sequences of same characters from string ideally without regex? - python-3.x

I have a sample string (actually it is much longer) that looks like this:
st='+++----++-++++-----'
I want to extract groups of '+' and '-' to produce the following result:
list_of_strings=['+++----', '++-', '++++-----']
This is what I tried and it apparantly doesnt work:
st='+++----++-++++-----'
group_st=''
for i, k in zip(st, st[1:]):
if i==k:
group_st+=i

Try:
st='+++----++-++++-----'
out, current = [], ''
for ch in st:
if current == '' or current[-1] == ch or ch == '-' and current[-1] == '+':
current += ch
else:
out.append(current)
current = ch
if current:
out.append(current)
print(out)
Prints:
['+++----', '++-', '++++-----']

Related

How can I extend a word with a loop with Python3?

I'm a beginner and I'm working on an assignment where I want Python to use user input and extend the word.
If user input is monkey the output (print) should be: m-oo-nnn-kkkk-eeeee-yyyyyy
This is my start but it only outputs: m-o-n-k-e-y
Do you have any hints on how I can go forth? https://codeshare.io/8p6nB4
inp = input("Give me a word to extend: ")
index = -len(inp)
ext_inp = ''
for letter in inp:
if index < 0:
ext_inp += inp[index] + '-'
index += 1
print(ext_inp)
word_to_be_extended = input("give me a word to extern:")
word_after_extend = ''
for i in range(len(word_to_be_extended)):
word_after_extend += word_to_be_extended[i] * (i+1)
if i != len(word_to_be_extended)-1:
word_after_extend += '-'
print(word_after_extend)

URL Encoding using a loop

I am trying to use the following function to return the string with every space replaced with a %20. However, it only prints out the '%20' in each of the print statement outputs. I am also trying to omit replacing the first space in a string. Any ideas? I know that there is library and a .replace() method that exits to solve this, but I want to use a for loop and conditionals.
def urlEncode(text):
result = ''
for i in text:
if i == ' ':
i = '%20'
result = result + i
return result
print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs "))
print(urlEncode("blue is greener than purple for sure"))
output is:
%20
%20%20%20%20
%20%20%20%20%20%20
Hey you need to add the characters that are not space too, right? Have a look in the edited script.
def urlEncode(text):
result = ''
for i in text:
if i == ' ':
i = '%20'
result += i
else:
result += i
return result
print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs "))
print(urlEncode("blue is greener than purple for sure"))
Edit, additional answer: -how to omit first space
def urlEncode(text):
result = ''
counter = 0
for i in text:
if(counter == 0 and text[counter] == ' '):
result += i
elif i == ' ':
i = '%20'
result += i
else:
result += i
counter += 1
return result

Encoding duplicate characters of a string in Python

I am trying to encode a string to replace a character with '(' if it occurs only once and with ')' if it occurs more than once. So "hello" becomes "(())(". I am using dictionary to solve this. I am saving the number of occurrences of each character in the string . Then I check if that character comes up more than once then I use .replace() to replace it with ')' else with '('. The problem happens when the string contains ')'.
So for example if I have the string "abca)". I should get ")(())" as the result but I get "(((((" cause when the program gets to ')' it sees it has occurred only once and then changes every occurrence of ')' with '('. It works fine rest of the time. Here's my code:
def duplicate_encode(word):
count = {}
word = word.lower()
for ch in word:
if ch in count:
count[ch] += 1
else:
count[ch] = 1
for k in count:
if count[k] > 1:
word = word.replace(k, ')')
else:
word = word.replace(k, '(')
print(word)
duplicate_encode("abca)")
Use the following code it will work
A=input()
b=list(A)
c=list(set(A))
for i in c:
if b.count(i)>1:
A=A.replace(i,")")
elif b.count(i)==1:
A=A.replace(i,"(")
print(A)
There are two mistakes in your code:
the only (and trailing) ( in word causes final word = replace(word, '(', ')') so that all (s are replaced with )s; therefore, I build the outword string from scratch;
len(count) < len(word) if there is any duplicate character in word; therefore, the k must iterate over word rather than over count.
Fixed code:
def duplicate_encode(word):
count = {}
outword = ''
word = word.lower()
for ch in word:
if ch in count:
count[ch] += 1
else:
count[ch] = 1
for k in word:
if count[k] > 1:
outword += ')'
else:
outword += '('
print( word, '=>', outword )
duplicate_encode("abca)")
duplicate_encode("hello")
Output: .\SO\67089558.py
abca) => )(()(
hello => (())(

Concatenating string outputs of a for loop in Python 3

I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?
You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)

Statement has no effect(Python)

program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t'
here's my code
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t:
each == '$'
else:
continue
return string
print(change("restart"))
output
restart
i'using Pycharm. Line no 6 (each == '$')says this statement has no effect. i don't want to use replace method. just want to know what is the problem.
Your code commented:
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t: # To compara strings you should use the == operator not the 'is' operator.
each == '$' # This will not have any effect because is a temporal variable visible just inside the 'for' loop and you are not using it.
else:
continue
return string
print(change("restart"))
A solution could be:
def change(s):
result = ''
for character in s:
result += '$' if character == s[0] else character
return result
print(change('restart'))
Python strings are immutable objects, so you can't do 'aaa'[1] = 'b' to get aba.
each is set to an integer and you are comparing it to a string.

Resources