Changing lowercase characters to uppercase and vice-versa in Python - python

I'm trying to write a function which given a string returns another string that flips its lowercase characters to uppercase and viceversa.
My current aproach is as follows:
def swap_case(s):
word = []
for char in s:
word.append(char)
for char in word:
if char.islower():
char.upper()
else:
char.lower()
str1 = ''.join(word)
However the string doesn't actually change, how should I alter the characters inside the loop to do so?
PS: I know s.swapcase() would easily solve this, but I want to alter the characters inside the string during a for loop.

def swap_case(s):
swapped = []
for char in s:
if char.islower():
swapped.append(char.upper())
elif char.isupper():
swapped.append(char.lower())
else:
swapped.append(char)
return ''.join(swapped)

you can use swapcase.
string.swapcase(s)
Return a copy of s, but with lower case letters converted to upper case and vice versa.
Source : Python docs

>>> name = 'Mr.Ed' or name= ["M","r",".","E","d"]
>>> ''.join(c.lower() if c.isupper() else c.upper() for c in name)
'mR.eD'

Your code is not working because you are not storing the chars after transforming them. You created a list with all chars and then, you access the values without actually saving them. Also, you should make your function return str1 or you will never get a result. Here's a workaround:
def swap_case(s):
word = []
for char in s:
if char.islower():
word.append(char.upper())
else:
word.append(char.lower())
str1 = ''.join(word)
return str1
By the way, I know you want to do it with a for loop, but you should know there are better ways to perform this which would be more pythonic.

You can use this code:
s = "yourString"
res = s.swapcase()
print(res)
Which will output:
YOURsTRING

def swap_case(s):
x = ''
for i in s:
if i.isupper():
i = i.lower()
else:
i = i.upper()
x += ''.join(i)
return x

Related

How to use a list of numbers as index inputs

So I have a list of numbers (answer_index) which correlate to the index locations (indicies) of a characters (char) in a word (word). I would like to use the numbers in the list as index inputs later (indexes) on in code to replace every character except my chosen character(char) with "*" so that the final print (new_word) in this instance would be (****ee) instead of (coffee). it is important that (word) maintains it's original value while (new_word) becomes the modified version. Does anyone have a solution for turning a list into valid index inputs? I will also except easier ways to meet my goal. (Note: I am extremely new to python so I'm sure my code looks horrendous) Code below:
word = 'coffee'
print(word)
def find(string, char):
for i, c in enumerate(string):
if c == char:
yield i
string = word
char = "e"
indices = (list(find(string, char)))
answer_index = (list(indices))
print(answer_index)
for t in range(0, len(answer_index)):
answer_index[t] = int(answer_index[t])
indexes = [(answer_index)]
new_character = '*'
result = ''
for i in indexes:
new_word = word[:i] + new_character + word[i+1:]
print(new_word)
You hardly ever need to work with indices directly:
string = "coffee"
char_to_reveal = "e"
censored_string = "".join(char if char == char_to_reveal else "*" for char in string)
print(censored_string)
Output:
****ee
If you're trying to implement a game of hangman, you might be better off using a dictionary which maps characters to other characters:
string = "coffee"
map_to = "*" * len(string)
mapping = str.maketrans(string, map_to)
translated_string = string.translate(mapping)
print(f"All letters are currently hidden: {translated_string}")
char_to_reveal = "e"
del mapping[ord(char_to_reveal)]
translated_string = string.translate(mapping)
print(f"'{char_to_reveal}' has been revealed: {translated_string}")
Output:
All letters are currently hidden: ******
'e' has been revealed: ****ee
The easiest and fastest way to replace all characters except some is to use regular expression substitution. In this case, it would look something like:
import re
re.sub('[^e]', '*', 'coffee') # returns '****ee'
Here, [^...] is a pattern for negative character match. '[^e]' will match (and then replace) anything except "e".
Other options include decomposing the string into an iterable of characters (#PaulM's answer) or working with bytearray instead
In Python, it's often not idiomatic to use indexes, unless you really want to do something with them. I'd avoid them for this problem and instead just iterate over the word, read each character and and create a new word:
word = "coffee"
char_to_keep = "e"
new_word = ""
for char in word:
if char == char_to_keep:
new_word += char_to_keep
else:
new_word += "*"
print(new_word)
# prints: ****ee

How to change case for alternative letters of a string

I would like to convert every other letter of a string into uppercase. For example provided the input is 'ahdjeryu', the result should be 'AhDjErYu'.
I was trying this:
def mycode(letters):
myword = letters.split()
for i in letters:
if i%2 == 0:
return i.upper()
else:
return i.lower()
print(mycode('ahdjeryu'))
The error thrown as:
if i%2==0:
TypeError: not all arguments converted during string formatting
Several issues with your code:
You only need to use str.split to remove whitespace. Here, not necessary.
To extract the index of a letter as well as the letter, use enumerate.
return will return just one letter. You can instead yield letters and then use str.join on the generator.
Here's a working example:
def mycode(letters):
for idx, i in enumerate(letters):
if idx % 2 == 0:
yield i.upper()
else:
yield i.lower()
print(''.join(mycode('ahdjeryu')))
AhDjErYu
The above logic can be equivalently implemented via a generator comprehension:
res = ''.join(i.upper() if idx % 2 == 0 else i.lower() for idx, i in enumerate(letters))
Your i is a string of one character, not an index. So you can't do i%2. Use enumerate to get both the index and the value.
alternating = ''.join(letter.upper() if index%2==0 else letter.lower() for index, letter in enumerate(text)
Yes, it error, cause i now is letter not a number, so it can't mod for 2.
Im not sure syntax about looping by for in Python but may you can try:
cnt = 0
for i in letters:
if cnt%2 == 0:
return i.upper()
else:
return i.lower()
cnt++
Hope it can help you!
Fix me if I have any wrong. Thanks
#Abhi, this is inline with your original logic. You need r to get the index of the letters in the string.
def mycode(letters):
for ch in letters:
r=letters.index(ch)
if r%2 == 0:
letters=letters.replace(ch,letters[r].upper())
else:
letters=letters.replace(ch,letters[r].lower())
return letters
print(mycode('ahdjeryu'))

How do I check if a string contains ALL letters of the alphabet in python?

I am trying to write a python program that checks if a given string is a pangram - contains all letters of the alphabet.
Therefore, "We promptly judged antique ivory buckles for the next prize" should return True while any string that does not contain every letter of the alphabet at least once should return False.
I believe I should be using RegEx for this one, but I'm not sure how. It should look similar to this:
import sys
import re
input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]
if (re.search('string contains every letter of the alphabet',input_string):
return True
else:
return False
This is not something I'd solve with a regular expression, no. Create a set of the lowercased string and check if it is a superset of the letters of the alphabet:
import string
alphabet = set(string.ascii_lowercase)
def ispangram(input_string):
return set(input_string.lower()) >= alphabet
Only if every letter of the alphabet is in the set created from the input text will it be a superset; by using a superset and not equality, you allow for punctuation, digits and whitespace, in addition to the (ASCII) letters.
Demo:
>>> import string
>>> alphabet = set(string.ascii_lowercase)
>>> input_string = 'We promptly judged antique ivory buckles for the next prize'
>>> set(input_string.lower()) >= alphabet
True
>>> set(input_string[:15].lower()) >= alphabet
False
This is my solution in python:
alphabet = "abcdefghijklmnopqrstuvwxyz"
sentence = input()
sentence = sentence.lower()
missing = ''
for letter in alphabet:
if letter not in sentence:
missing = missing+letter
if (len(missing) != 0):
print("missing", missing)
else:
print("pangram")
You dont need regex. What you want can be done in two lines with good space efficiency.
ms = itertools.chain(range(ord("a"),ord("z")),range(ord("A"),ord("Z")))
flag = all(chr(o) in string for o in ms)
That's it. string is the string you want to check. flag will be either True or False depending on if all chars are in string or not.
A pangram is a function that contains at least each letter of the alphabet.
I have tried in this way:
def pangram():
n = str(input('give me a word to check if it is a pangram:\n'))
n = n.lower()
n = n.replace(' ','')
if not isinstance(n, str):
return n, False
elif set(n) >= set('abcdefghijklmnopqrstuvxywz'):
return n, True
else:
return n, False
The function isinstance(n, str) checks if n is a string. The function set() gives us a set. For example set('penny') returns {'y', 'e', 'p', 'n'}... as you see it is a set without the repeated letters.
I was doing the same exercise today, maybe it's not the best aproach, but I think it's easy to understand.
def ispangram(s):
stringy = ''
flag = True
validLetters = "abcdefghijklmnopqrstuvwxyz"
#transform the given string in simple string with no symbols only letters
for char in s.lower():
if(char in validLetters):
stringy += char
#check if all the letters of the alphabet exist on the string
for char in validLetters:
if(char in stringy):
pass
else:
flag = False
break
return flag
if(ispangram("We promptly judged antique ivory buckles for the next prize")):
print("It's PANGRAM!")
else:
print("It's not Pangram :(")
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
return ''.join(sorted(set(str1.lower().replace(" ","")))) == alphabet
First changed all alphabets to lowercase and then removed all spaces using replace. Then Converted into set to have unique chars and then used sorted function to sort alphabetically. As sorted function gives a list, so join func to join it without spaces and then compared it to all lowercase chars.
Here is my solution:
def isaPangrams(s):
alph = list(string.ascii_lowercase)
s = s.lower()
s = list(s)
for letter in alph:
if letter not in s:
print('not pangram')
present='false'
break
if letter in s:
present = 'true'
if present == 'true':
print('pangram')
if __name__ == '__main__':
s = input()
answer = isaPangrams(s)

Swapping uppercase and lowercase in a string [duplicate]

This question already has answers here:
How can I invert (swap) the case of each letter in a string?
(8 answers)
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 6 months ago.
I would like to change the chars of a string from lowercase to uppercase.
My code is below, the output I get with my code is a; could you please tell me where I am wrong and explain why?
Thanks in advance
test = "AltERNating"
def to_alternating_case(string):
words = list(string)
for word in words:
if word.isupper() == True:
return word.lower()
else:
return word.upper()
print to_alternating_case(test)
If you want to invert the case of that string, try this:
>>> 'AltERNating'.swapcase()
'aLTernATING'
There are two answers to this: an easy one and a hard one.
The easy one
Python has a built in function to do that, i dont exactly remember what it is, but something along the lines of
string.swapcase()
The hard one
You define your own function. The way you made your function is wrong, because
iterating over a string will return it letter by letter, and you just return the first letter instead of continuing the iteration.
def to_alternating_case(string):
temp = ""
for character in string:
if character.isupper() == True:
temp += character.lower()
else:
temp += word.upper()
return temp
Your loop iterates over the characters in the input string. It then returns from the very first iteration. Thus, you always get a 1-char return value.
test = "AltERNating"
def to_alternating_case(string):
words = list(string)
rval = ''
for c in words:
if word.isupper():
rval += c.lower()
else:
rval += c.upper()
return rval
print to_alternating_case(test)
That's because your function returns the first character only. I mean return keyword breaks your for loop.
Also, note that is unnecessary to convert the string into a list by running words = list(string) because you can iterate over a string just as you did with the list.
If you're looking for an algorithmic solution instead of the swapcase() then modify your method this way instead:
test = "AltERNating"
def to_alternating_case(string):
res = ""
for word in string:
if word.isupper() == True:
res = res + word.lower()
else:
res = res + word.upper()
return res
print to_alternating_case(test)
You are returning the first alphabet after looping over the word alternating which is not what you are expecting. There are some suggestions to directly loop over the string rather than converting it to a list, and expression if <variable-name> == True can be directly simplified to if <variable-name>. Answer with modifications as follows:
test = "AltERNating"
def to_alternating_case(string):
result = ''
for word in string:
if word.isupper():
result += word.lower()
else:
result += word.upper()
return result
print to_alternating_case(test)
OR using list comprehension :
def to_alternating_case(string):
result =[word.lower() if word.isupper() else word.upper() for word in string]
return ''.join(result)
OR using map, lambda:
def to_alternating_case(string):
result = map(lambda word:word.lower() if word.isupper() else word.upper(), string)
return ''.join(result)
You should do that like this:
test = "AltERNating"
def to_alternating_case(string):
words = list(string)
newstring = ""
if word.isupper():
newstring += word.lower()
else:
newstring += word.upper()
return alternative
print to_alternating_case(test)
def myfunc(string):
i=0
newstring=''
for x in string:
if i%2==0:
newstring=newstring+x.lower()
else:
newstring=newstring+x.upper()
i+=1
return newstring
contents='abcdefgasdfadfasdf'
temp=''
ss=list(contents)
for item in range(len(ss)):
if item%2==0:
temp+=ss[item].lower()
else:
temp+=ss[item].upper()
print(temp)
you can add this code inside a function also and in place of print use the return key
string=input("enter string:")
temp=''
ss=list(string)
for item in range(len(ss)):
if item%2==0:
temp+=ss[item].lower()
else:
temp+=ss[item].upper()
print(temp)
Here is a short form of the hard way:
alt_case = lambda s : ''.join([c.upper() if c.islower() else c.lower() for c in s])
print(alt_case('AltERNating'))
As I was looking for a solution making a all upper or all lower string alternating case, here is a solution to this problem:
alt_case = lambda s : ''.join([c.upper() if i%2 == 0 else c.lower() for i, c in enumerate(s)])
print(alt_case('alternating'))
You could use swapcase() method
string_name.swapcase()
or you could be a little bit fancy and use list comprehension
string = "thE big BROWN FoX JuMPeD oVEr thE LAZY Dog"
y = "".join([val.upper() if val.islower() else val.lower() for val in string])
print(y)
>>> 'THe BIG brown fOx jUmpEd OveR THe lazy dOG'
This doesn't use any 'pythonic' methods and gives the answer in a basic logical format using ASCII :
sentence = 'aWESOME is cODING'
words = sentence.split(' ')
sentence = ' '.join(reversed(words))
ans =''
for s in sentence:
if ord(s) >= 97 and ord(s) <= 122:
ans = ans + chr(ord(s) - 32)
elif ord(s) >= 65 and ord(s) <= 90 :
ans = ans + chr(ord(s) + 32)
else :
ans += ' '
print(ans)
So, the output will be : Coding IS Awesome

Python: Best Way to remove duplicate character from string

How can I remove duplicate characters from a string using Python? For example, let's say I have a string:
foo = "SSYYNNOOPPSSIISS"
How can I make the string:
foo = SYNOPSIS
I'm new to python and What I have tired and it's working. I knew there is smart and best way to do this.. and only experience can show this..
def RemoveDupliChar(Word):
NewWord = " "
index = 0
for char in Word:
if char != NewWord[index]:
NewWord += char
index += 1
print(NewWord.strip())
NOTE: Order is important and this question is not similar to this one.
Using itertools.groupby:
>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'
This is a solution without importing itertools:
foo = "SSYYNNOOPPSSIISS"
''.join([foo[i] for i in range(len(foo)-1) if foo[i+1]!= foo[i]]+[foo[-1]])
Out[1]: 'SYNOPSIS'
But it is slower than the others method!
How about this:
oldstring = 'SSSYYYNNNOOOOOPPPSSSIIISSS'
newstring = oldstring[0]
for char in oldstring[1:]:
if char != newstring[-1]:
newstring += char
def remove_duplicates(astring):
if isinstance(astring,str) :
#the first approach will be to use set so we will convert string to set and then convert back set to string and compare the lenght of the 2
newstring = astring[0]
for char in astring[1:]:
if char not in newstring:
newstring += char
return newstring,len(astring)-len(newstring)
else:
raise TypeError("only deal with alpha strings")
I've discover that solution with itertools and with list comprehesion even the solution when we compare the char to the last element of the list doesn't works
def removeDuplicate(s):
if (len(s)) < 2:
return s
result = []
for i in s:
if i not in result:
result.append(i)
return ''.join(result)
How about
foo = "SSYYNNOOPPSSIISS"
def rm_dup(input_str):
newstring = foo[0]
for i in xrange(len(input_str)):
if newstring[(len(newstring) - 1 )] != input_str[i]:
newstring += input_str[i]
else:
pass
return newstring
print rm_dup(foo)
You can try this:
string1 = "example1122334455"
string2 = "hello there"
def duplicate(string):
temp = ''
for i in string:
if i not in temp:
temp += i
return temp;
print(duplicate(string1))
print(duplicate(string2))

Categories

Resources