Remove previous letter if '/' Python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
I'm trying to write a simple program where it removes the previous letter when there exists a "/" after the character. Also, if there are two "//" after two characters, it should remove the last two characters. The number of / only exists if there a similar number of characters before so // in this scenario: aa//.
for example
x = 'abc/c/dd//a'
print x.rstrip('/')
it should return
aba
another example
x = '/aab//'
print x.rstrip('/')
should return
a
I have seen solutions trying the method above, but it doesn't seem to work for me. Is there an optimal solution for this?

A simple function can do this :
def stripStr(x, special_char="/"):
buff = ""
for char in x:
if char == special_char:
buff = buff[:-1]
else:
buff += char
return buff
assert stripStr('abc/c/dd//a') == 'aba'
assert stripStr('abc////cde/dd///a') == 'ca'
The idea is to reconstruct the string (in the buff variable) character after character. You simply need to keep appending each char except when you find a / then you have to remove the last char of the string.

Related

I need help (with def) print out some alphabet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
currently I faced issue with python code
I have two questions relate with "def" code.
1)
I need to print out 6 alphabet which is "K,E,Y,S,N,O"
slimier like under sample
enter image description here
2)
how can I print out this alphabet if user typing one word like "KEY" then print out *mark with KEY
or If user typing "BED" then print out "E"only because we only have alphabet with K,E,Y,S,N,O
if can anyone help me with this two questions? I appreciate that
Thanks
Question 1 need work with 2-dimensional list (list with lists for rows) and I skip this problem.
As for Question 2 you can filter chars in word.
You can treat string "BED" as list of chars (even without using list("BED")) and you can use it in for-loop to check every char with list ["K","E","Y","S","N","O"] (or "KEYSNO") and skip chars "B" and "D"
#my_chars = "KEYSNO" # also works
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
for char in word:
if char in my_chars:
print(char, "- OK")
else:
print(char, "- unknown")
Result:
B - unknown
E - OK
D - unknown
This way you can create new list to keep only correct chars
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
filtered_chars = []
for char in word:
if char in my_chars:
filtered_chars.append(char)
print(filtered_chars)
Result:
['E']
In Python you can write it even shorter using list comprehension
filtered_chars = [char for char in word if char in my_chars]
Eventually you can write it with function filter() like
filtered_chars = list(filter(lambda char: char in my_chars, word))

Checking whether last element of list is digit [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a function generating random character [a-Z0-9] with whitespaces and appending each character to list:
words = []
while words.count(' ') < 10:
if len(words) == 0:
# append character
else:
if words[-1].isdigit(): # checking if last character is digit
# append only digit or whitespacce
else:
# append character
As you can see if last (previous) character was digit, I try to append digit or whitespace only, otherwhise append any character. The problem is, when I run the code I get error below:
'NoneType' object has no attribute 'isdigit' for line if words[-1].isdigit():. What I do wrong and why there is None instead of str?
Just make words string:
(It's biased towards chars, because whitespace is not digit, and hence it can turn to chars from digits, but not other way around- which is what you wanted, if I got you right)
import random
sample_digit=" 0123456789"
sample_char=" abcdefghi"
sample_any=sample_digit+sample_char
words = ""
while words.count(' ') <10:
if len(words) == 0:
words+=sample_any[random.randint(0, len(sample_any)-1)]
else:
if words[-1].isdigit():
words+=sample_digit[random.randint(0, len(sample_digit)-1)]
else:
words+=sample_char[random.randint(0, len(sample_char)-1)]
print(words)
A simple way of testing whether a character is a digit:
if words[-1] in '0123456789':
...

Error in program-censor(codecademy)Practice makes perfect [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wanted to include spaces too while splitting the text, for that i looked up on google used import re
import re
def censor(text,word) :
text1=re.split(r"(\s+)",text)
#print text1
sum=""
for i in range(0,len(text1)) :
if text1[i]==word :
for j in range(0,len(word)) :
sum=sum+"*"
else :
sum=sum+text[i]
return sum
The error I am getting is
image displaying error and code
If I include an another for loop to replace every 'e' with a whitespace , it doesn't work.
In your code, text1 (very bad naming BTW) is a list of words, and text a single string. Your first for loop is iterating on text1 indices (words in the list), but in the else clause you subscript the whole text string. Obviously you want to get the word from the words list (text1), not the character at position i in the text string. IOW: replace your else clause with:
sum=sum+text1[i]
and the test should pass.
If you used a correct naming and proper code layout you would certainly have spotted the problem more easily:
def censor(text, word) :
words = re.split(r"(\s+)",text)
sum=""
for i in range(0, len(words)) :
if words[i] == word :
for j in range(0, len(word)) :
sum = sum + "*"
else :
# here you easily spot the error
sum = sum + text[i]
return sum
Also you are making things much more complicated than they have to be. You can pre-compute the "replacement" string for "bad" words once for all before the loop (and you don't need a loop to do so), and you don't need a range and indexed acces, ou can iterate directly on the words list instead:
def censor(text, word) :
replacement = "*" * len(word)
words = re.split(r"(\s+)", text)
cleaned = ""
for w in words :
if w == word :
cleaned += replacement
else :
cleaned += w
return cleaned
There would be other possible improvements but at least this is mostly readable and much more pythonic.

Why doesn't my front_back programme in Python work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The task is:
Given a string, return a new string where the first and last chars have been exchanged.
def front_back(str):
if len(str)<=0:
return str
else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2
front_back("code")
Why?
It won't work because .replace() will replace all occurrences of that character, not necessarily only the first and last
Below is a solution that constructs the string with first, body and last portions
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
String literals can be sliced and added:
>>> s = "hello world"
>>> s[-1] + s[1:-1] + s[0]
'dello worlh'
P.S. str is a builtin in python, so using it as a variable name is a bad idea.
First, never call a variable str. Why? Because that is the name of the class for Python strings. If you use the same name then you loose it. I use txt.
Your test with the length is sensible, but the lower limit can be increased (a single character would be silly).
But using str.replace() is not feasible. Why? Well it could work in your test case, but only because each character is unique. str.replace() replaces every occurrence of the specified string. So if the first or last character was repeated elsewhere then that would be changed as well.
You can use slicing, where the first (leftmost) character is 0 (zero). You can also index from the right using negative numbers, so -1 is the last (rightmost) character. The range of characters goes from the start to the character after the last. So [1:-1] goes from the second character to the last but one.
def front_back(txt):
if len(txt) <= 1:
return txt
else:
new_txt = txt[-1] + txt[1:-1] + txt[0]
return new_txt
print front_back("code")
I use return in the function, since that would be the normal way of processing text, and that is asked for in your question.

Replacing the last three characters in a string if they match a condition [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to take a user inputed string and, if it ends with 'ion', replace the last three characters of the string and add an 'e'.
def ion2e(s):
if s[-3:]=='ion':
print (s[-3:]+'e')
else:
print (s)
Use str.endswith:
>>> def ion2e(s):
... return s[:-3] + 'e' if s.endswith('ion') else s
...
>>> ion2e('xxxion')
'xxxe'
>>> ion2e('xx')
'xx'
s[-3:] says
give me s starting 3 digits backwards from the end, and going to the end
But what you want is s up to 3 digits backwards from the end. Which would be:
s[:-3]
So your whole code should be:
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
Move the colon in your print. You need the string up to the -3rd element, not the end of the string.
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
t = "constitution"
ion2e(t)
Also, are you familiar with single-statement if expressions? Your function might be reduced to this, if you want to return the value instead of printing it.
def ion2e(s):
return s[:-3]+'e' if s[-3:]=='ion' else s
You may also want to use re
import re
print (re.sub("ion$", "e", 'station'))

Categories

Resources