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.
Related
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.
I want to know how you can replace one letter of a string without replacing the same letter. For example, let the variable:
action = play sports.
I could substitute "play" for "playing" by doing print(action.replace("play", "playing")
But what if you have to of the same letters?
For example, what if you want to replace the last half of "honeyhoney" into "honeysweet" (Replacing the last half of the string to sweet?
Sorry for the bad wording, I am new to coding and really unfamiliar with this. Thanks!
def replaceLast(str, old, new):
return str[::-1].replace(old[::-1],new[::-1], 1)[::-1]
print(replaceLast("honeyhoney", "honey", "sweet"))
output
honeysweet
so the idea is to reverse the string and the old and new substrings,
so the last substring becomes the first, do a replace and then reverse the returned string once again, and the number 1 is to replace only once and not both matches
Another solution
def replaceLast(str, old, new):
ind = str.rfind(old)
if ind == -1 : return str
return str[:ind] + new + str[ind + len(old):];
print(replaceLast("honeyhoney", "honey", "sweet"))
output
honeysweet
so here we get the string from the beginning to the index of the last substring then we add the new substring and the rest of the string from where the old substring ends and return them as the new string, String.rfind returns -1 in case of no match found and we need to check aginst that to make sure the output is correct even if there is nothing to replace.
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':
...
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 4 years ago.
Improve this question
def LongestWord(sen):
# first we remove non alphanumeric characters from the string
# using the translate function which deletes the specified characters
sen = sen.translate(None, "~!##$%^&*()-_+={}[]:;'<>?/,.|`")
# now we separate the string into a list of words
arr = sen.split(" ")
print(arr)
# the list max function will return the element in arr
# with the longest length because we specify key=len
return max(arr, key=len)
**print LongestWord("Argument goes here")**
what's wrong with this line? How can I change it? I can't understand it! It make me really uneasy, cause in Coderbyte.com says that it is true and it work!
I'm not exactly sure what line you're referring too? Perhaps the last line.
If so you need a parenthesis with the print statement in python 3.x
print(LongestWord("Argument goes here"))
additionally, string translate works differently in python 3
def LongestWord(sen):
# first we remove non alphanumeric characters from the string
# using the translate function which deletes the specified characters
intab ="~!##$%^&*()-_+={}[]:;'<>?/,.|`"
trantab= str.maketrans(dict.fromkeys(intab))
sen = sen.translate(trantab)
# now we separate the string into a list of words
arr = sen.split(" ")
print(arr)
# the list max function will return the element in arr
# with the longest length because we specify key=len
return max(arr, key=len)
print(LongestWord("Argument. 'Go' #goes here"))
The above worked for me on python 3.6.2
It is working properly but instead of return try
print max(arr, key=len)
as if you called the function directly without print keyword preceding it won't show the max or you can return both arr, max in single line and print the function output so it would look like this:
def LongestWord(sen):
sen = sen.translate(None, "~!##$%^&*()-_+={}[]:;'<>?/,.|`")
arr = sen.split(" ")
print(arr)
print max(arr, key=len)
LongestWord("Argument goes here ! #")
NOTE : it worked in Python 2.7
IF YOU WOULD LIKE TO USE PYTHON 3.7
use the following
to_remove = sen.maketrans("", "", "~!##$%^&*()-_+={}[]:;'<>?/,.|`")
sen = sen.translate(to_remove)
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'))