This question already has answers here:
How can I invert (swap) the case of each letter in a string?
(8 answers)
Closed 6 months ago.
this script is supposed to swap case in words but the result is really weird and doesn't make sense
def swap_case(s):
for i in range(len(s)):
if s[i].islower():
s= s.replace(s[i],s[i].upper())
elif s[i].isupper():
s= s.replace(s[i],s[i].lower())
else:
pass
example
First of all consider using inbuild swapcase function
Otherwise, you can use join function
E.g.
s = "hELLO wORLD"
# inbuilt
print(s.swapcase())
# join
print(''.join([ss.lower() if ss.isupper() else ss.upper() for ss in s]))
which gives you
You're going through each letter in the string, then replacing all instances of that letter. That means that if there's an even amount of a letter, the case won't be changed.
Also, a method, swapcase, already exists for this.
>>> 'Hello World!'.swapcase()
'hELLO wORLD!'
Here is the solution for your problem-->
def swap_case(s):
k=''
for i in range(len(s)):
if s[i].islower():
k+=s[i].upper()
elif s[i].isupper():
k+=s[i].lower()
else:
pass
print(k)
Solution with Python
Case Swapping can be achieve using a python built-in function called swapcase if you want to do this manually then here is the code.
result = ''
for element in (s):
if element.isupper():
result += element.lower()
else:
result += element.upper()
print(result)
Related
This question already has answers here:
Understanding slicing
(38 answers)
Closed 5 months ago.
s = "aB:cD"
def transform_string():
string_Length = len(s)
pos_colon = s.find(":")
lowerCase = s.lower()
upperCase = s.upper()
string_partA = 0 + pos_colon
res = lowerCase[:string_partA] + upperCase[string_partA:]
return res
print(transform_string())
print()
The code is meant to have the part of the string before the colon lowercased and after the colon uppercased. So my question is what is
res = lowerCase[:string_partA] + upperCase[string_partA:]
the bracket in there is meant to be for, or more explicitly, when can we use that? Does that syntax have a name? I saw someone else use it and I could logically follow how it works and what it does, I just wonder if that has a name or syntax restrictions and so on...
I first tried to use a for loop (would appreciate if someone could tell me why that is wrong, I know it's not as efficient as the code above):
s = "aB:cD"
def transform_string():
y = len(s)
x = s.find(":")
for s in range(0, x):
first_half = s.lower()
for s in range(x, y):
second_half = s.upper()
res = f"{first_half}+{second_half}"
return res
print(transform_string())
print()
Thanks!
The reason you are wrong is that you want to (lower) or (upper) (an integer).
When you put S in suffering, your S is equal to Integer
The first time (S=0), the second time (S=1) and so on until the end
But the above code finds out which section should be (lower) or (upper) by indexing
Meanwhile, when you want to get (Lens) because (S) is defined outside the function, (Len) cannot be calculated.
It is enough to write (global s) inside the function or give (s) as input to the function.
This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
return statement in for loops [duplicate]
(6 answers)
Closed 1 year ago.
Please see the below code
def common_letters(string_one,string_two):
letters_in_common = []
for letter in string_one:
for letter2 in string_two:
if letter == letter2:
letters_in_common.append(letter)
return letters_in_common
returned = common_letters("hello", "loha")
print(returned)
The above code works, but only on the first iteration of the outer loop, hence my letters_in_common list only returns ['h'] when it should return ['h','l','l'], In JS the syntax is different and the loop works incrementally.
Am I misunderstanding how loops work in Python or is there a syntax level step I have not included?
p.s. I am aware that I could use the 'in' keyword etc but I wanted to try it with a loop first.
Your return is indented so that it is inside if. Presumably you want to return after you check every letter against every letter, which means return has to be outside the loops:
def common_letters(string_one, string_two):
letters_in_common = []
for letter in string_one:
for letter2 in string_two:
if letter == letter2:
letters_in_common.append(letter)
return letters_in_common
Sidenote: This will give a somewhat surprising result if there are multiples of a shared letter in both strings. If I wanted to find out just the shared letters, I would use set intersection:
def common_letters(string_one, string_two):
return list(set(string_one) & set(string_two))
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
n = n + 1
result = s[ start: n ] + " " + result
start = n
return result
But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much.
Any help would be appreciated.
def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
(Very few people do heavy recursive processing in Python, the language wasn't designed for it.)
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right?
So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as x[-1] while everything but the last character is x[:-1].
Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done.
But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, also be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set.
Put it all together and you get:
def backward(text):
if text == "":
return text
else:
return text[-1] + backward(text[:-1])
Or in one line:
backward = lambda t: t[-1] + backward(t[:-1]) if t else t
As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still.
Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
I just want to add some explanations based on Fred Foo's answer.
Let's say we have a string called 'abc', and we want to return its reverse which should be 'cba'.
def reverse(s):
if s == "":
return s
else:
return reverse(s[1:]) + s[0]
s = "abc"
print (reverse(s))
How this code works is that:
when we call the function
reverse('abc') #s = abc
=reverse('bc') + 'a' #s[1:] = bc s[0] = a
=reverse('c') + 'b' + 'a' #s[1:] = c s[0] = a
=reverse('') + 'c' + 'b' + 'a'
='cba'
If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do s[::-1].
def reverse_string(s):
if s: return s[-1] + reverse_string(s[0:-1])
else: return s
or
def reverse_string(s):
return s[-1] + reverse_string(s[0:-1]) if s else s
I know it's too late to answer original question and there are multiple better ways which are answered here already. My answer is for documentation purpose in case someone is trying to implement tail recursion for string reversal.
def tail_rev(in_string,rev_string):
if in_string=='':
return rev_string
else:
rev_string+=in_string[-1]
return tail_rev(in_string[:-1],rev_string)
in_string=input("Enter String: ")
rev_string=tail_rev(in_string,'')
print(f"Reverse of {in_string} is {rev_string}")
s = input("Enter your string: ")
def rev(s):
if len(s) == 1:
print(s[0])
exit()
else:
#print the last char in string
#end="" prints all chars in string on same line
print(s[-1], end="")
"""Next line replaces whole string with same
string, but with 1 char less"""
return rev(s.replace(s, s[:-1]))
rev(s)
if you do not want to return response than you can use this solution. This question is part of LeetCode.
class Solution:
i = 0
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if self.i >= (len(s)//2):
return
s[self.i], s[len(s)-self.i-1] = s[len(s)-self.i-1], s[self.i]
self.i += 1
self.reverseString(s)
This question already has answers here:
How can I find all common letters in a set of strings?
(2 answers)
Closed 8 years ago.
I need to make a function that takes two string arguments and returns a string with only the characters that are in both of the argument strings. There should be no duplicate characters in the return value.
this is what I have but I need to make it print things only once if there is more then one
def letter(x,z):
for i in x:
for f in z:
if i == f:
s = str(i)
print(s)
If the order is not important, you can take the intersection & of the set of characters in each word, then join that set into a single string and return it.
def makeString(a, b):
return ''.join(set(a) & set(b))
>>> makeString('sentence', 'santa')
'nts'
Try this
s = set()
def letter(x,z):
for i in x:
for f in z:
if i == f:
s.add(i)
letter("hello","world")
print("".join(s))
It will print 'ol'
If sets aren't your bag for some reason (perhaps you want to maintain the order in one or other of the strings, try:
def common_letters(s1, s2):
unique_letters = []
for letter in s1:
if letter in s2 and letter not in unique_letters:
unique_letters.append(letter)
return ''.join(unique_letters)
print(common_letters('spam', 'arthuprs'))
(Assuming Python 3 for the print()).
This question already has answers here:
Python: Find a substring in a string and returning the index of the substring
(7 answers)
Closed 2 years ago.
I'm new to python and I'm trying different methods to accomplish the same task, right now I'm trying to figure out how to get a substring out of a string using a for loop and a while loop. I quickly found that this is a really easy task to accomplish using regex. For example if I have a string: "ABCDEFGHIJKLMNOP" and I want to find if "CDE" exists then print out "CDE" + the rest of the string how would I do that using loops? Right now I'm using:
for i, c in enumerate(myString):
which returns each index and character, which I feel is a start but I can't figure out what to do after. I also know there are a lot of build in functions to find substrings by doing: myString.(Function) but I would still like to know if it's possible doing this with loops.
Given:
s = 'ABCDEFGHIJKLMNOP'
targets = 'CDE','XYZ','JKL'
With loops:
for t in targets:
for i in range(len(s) - len(t) + 1):
for j in range(len(t)):
if s[i + j] != t[j]:
break
else:
print(s[i:])
break
else:
print(t,'does not exist')
Pythonic way:
for t in targets:
i = s.find(t)
if i != -1:
print(s[i:])
else:
print(t,'does not exist')
Output (in both cases):
CDEFGHIJKLMNOP
XYZ does not exist
JKLMNOP
Here's a concise way to do so:
s = "ABCDEFGHIJKLMNOP"
if "CDE" in s:
print s[s.find("CDE")+len("CDE"):]
else:
print s
Prints:
FGHIJKLMNOP
The caveat here is of course, if the sub-string is not found, the original string will be returned.
Why do this? Doing so allows you to check whether or not the original string was found or not. As such, this can be conceptualized into a simple function (warning: no type checks enforced for brevity - it is left up to the reader to implement them as necessary):
def remainder(string, substring):
if substring in string:
return string[string.find(substring)+len(substring):]
else:
return string
Getting the remainder of the string using a for-loop:
n = len(substr)
rest = next((s[i+n:] for i in range(len(s) - n + 1) if s[i:i+n] == substr),
None) # return None if substr not in s
It is equivalent to:
_, sep, rest = s.partition(substr)
if substr and not sep: # substr not in s
rest = None