I am new to programming and I need some help for an free online tutorial to learn Python. I am building my own method to convert a an input string to all lower cases. I cannot use the string.lower() method. In the code I have so far I cannot figure out how to separate the input string into characters that can be inputed into my character converter lowerChar(char).
string=input #input string
def lowerChar(char): #function for converting characters into lowercase
if ord(char) >= ord('A') and ord(char)<=ord('Z'):
return chr(ord(char) + 32)
else:
return char
def lowerString(string): #function for feeding characters of string into lowerChar
result = ""
for i in string:
result = result + lowerChar(string[i])
return result
You are really close:
def lowerString(string):
result = ""
for i in string:
# i is a character in the string
result = result + lowerChar(i)
# This shouldn't be under the for loop
return result
Strings are iterable just like lists!
Also, make sure to be careful about your indentation levels, and the number of spaces you use should be consistent.
You are returning only the first letter, you have to return in a outer scope, try this, also it is better to use += instead of result = result + lowerChar(i)
def lowerString(string): #function for feeding characters of string into lowerChar
result = ""
for i in string:
result += lowerChar(i)
return result
print lowerString("HELLO") #hello
A tip: You don't need to use ord(). Python can directly do the following comparision:
if char >= 'A' and char<='Z':
My solution:
string = input("Input one liner: ")
def lowerChar(char):
if char >= 65 and char <= 90:
char = chr(char + 32)
return char
else:
char = chr(char)
return char
def lowerString(string):
result = ""
for i in range(0, len(string)):
result = result + lowerChar(ord(string[i]))
return result
print(lowerString(string))
Try something like this:
def lowerChar(c):
if 'A' <= c <= 'Z':
return chr(ord(c) - ord('A') + ord('a'))
else:
return c
def lowerString(string):
result = ""
x=0
for i in string:
while x < len(string):
result = result + lowerChar(string[x])
x+=1
return result
Related
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
I am trying to perform conversion from a lowercase to uppercase on a string without using any inbuilt functions (other than ord() and char()). Following the logic presented on a different thread here , I came up with this.
def uppercase(str_data):
ord('str_data')
str_data = str_data -32
chr('str_data')
return str_data
print(uppercase('abcd'))
However I am getting an error output: TypeError: ord() expected a character, but string of length 8 found.What am I missing here?
You need to execute ord() for each character of your input string. instead of the input string:
def uppercase(str_data):
return ''.join([chr(ord(char) - 32) for char in str_data if ord(char) >= 65])
print(uppercase('abcdé--#'))
>>> ABCDÉ
Without join:
def uppercase(str_data):
result = ''
for char in str_data:
if ord(char) >= 65:
result += chr(ord(char) - 32)
return result
print(uppercase('abcdé--#λ'))
>>> ABCDÉΛ
The best way, in my opinion is using a helper string, representing the alphabet, if you do not want to use chr() and ord():
def toUppercase(s):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = ''
for x in s:
if x not in alphabet or alphabet.index(x)>=26:
result += x
else:
result += alphabet[alphabet.index(x)+26]
return result
This also handles punctuation such as ; or ..
Update:
As per the OP's request, this is a version without index():
def toUppercase(s):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = ''
for x in s:
for pos in range(52):
if alphabet[pos] == x:
i = pos
if x not in alphabet or i>=26:
result += x
else:
result += alphabet[i+26]
return result
print(toUppercase('abcdj;shjgh'))
Here is a program to convert the string to uppercase without using inbuilt functions:
Str1=input("Enter the string to be converted uppercase: ")
for i in range (0,len(Str1)):
x=ord(Str1[i])
if x>=97 and x<=122:
x=x-32
y=chr(x)
print(y,end="")
ord()- Return the Unicode code point for a one-character string.
You have to send a one character string as an argument. Here, you are sending the string 'abcd' which has 4 characters which is causing the issue. Send each character separately to the function and thus do 4 calls to the function to get the result.
The below-simplified code help to convert Lower-case alphabets to Upper-case alphabets using a simple calculation
code :
def toUppercase(string):
convertedCharacter = ''
for i in string:
convertCharacter += chr( ( (ord(i)) -32) )
return convertCharacter
char=input("Enter lowercase word :")
for letter in char:
s=ord(letter)
if s>=97 and s<=122:
print(chr(s-32),end=" ")
def uppercase(str_data):
ord('str_data')
str_data = str_data -32
chr('str_data')
return str_data
print(uppercase('abcd'))
in this code ord takes single character as an argument but you have given more than one that's why it's showing an error. Take single character at a time convert it to upper case and make a single string like below.
def convert_to_lower(string):
new=""
for i in string:
j=ord(i)-32 #we are taking the ascii value because the length of lower
#case to uppercase is 32 so we are subtracting 32
if 97<=ord(i)<=122 : #here we are checking whether the charecter is lower
# case or not if lowercase then only we are converting into
#uppercase
new=new+chr(j)
else: #if the character is not the lowercase alplhaber we are taking as it is
new=new+i
print(new)
convert_to_lower("hello world")
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
Write a function which accepts an input string and returns a string
where the case of the characters are changed, i.e. all the uppercase
characters are changed to lower case and all the lower case characters
are changed to upper case. The non-alphabetic characters should not be
changed. Do NOT use the string methods upper(), lower(), or swap().
This is my code:
def changing_cases (input_str):
new_string = []
for i in range(0, len(input_str)):
convert = input_str[i]
value = ord(convert)
if (value >= 65 and value <= 90 ):
value += 32
new_string.append(chr(value))
elif (value >= 97 and value <= 122):
value -= 32
new_string.append(chr(value))
return (str(new_string))
#Main Program
input_str = "Hello"
result = changing_cases (input_str)
print (result)
This code works as expected but there are two major problems with this.
Firstly the output which it returns to the Main is a list, I want it as a string.
Second, how to check whether the string contains special cases and by pass it if there is a special character. Special characters are scattered all over the ASCII table.
Any help would be appreciated.
The string method .join() can help you to unite a list and return a string. But without that knowledge, you could have done this string concatenation.(For that you need to initialize new_string with "", not [])
Join usage:
"".join(["h","e","l","l","o"])
# "hello"
To your second question. You could check if an input is from the alphabet with the .isalpha() method. Which returns a boolean value.
"a".isalpha()
# True
"&".isalpha()
# False
And a suggestion about the solution, You could import the uppercase and lowercase alphabets from the string module. After that, iterating over the term and swapping letters using the alphabet strings is very easy. Your solution is fine for understanding how ascii table works. But with the way I mentioned, you can avoid facing problems about special cases. It is a poor method for cryptology though.
Concerning the first problem. I've found it may be possible to use:
print ','.join(result)
or
print str(result).strip('[]')
Good luck!
def changing_cases (input_str):
new_string = []
for i in range(0, len(input_str)):
convert = input_str[i]
value = ord(convert)
if 65 <= value <= 90:
value += 32
new_string.append(chr(value))
elif 97 <= value <= 122:
value -= 32
new_string.append(chr(value))
else:
return
return ''.join(new_string)
So this function will return None if there are any special characters in string and you simply add if conditon to check if result is None then you just skip this word
You are close:
def changing_cases (input_str):
new_string = []
for i in range(0, len(input_str)):
convert = input_str[i]
value = ord(convert)
if (value >= 65 and value <= 90 ):
value += 32
new_string.append(chr(value))
elif (value >= 97 and value <= 122):
value -= 32
new_string.append(chr(value))
else: #if special character
new_string.append(chr(value))
return (''.join(new_string))
#Main Program
input_str = "Hello"
result = changing_cases (input_str)
print (result)
In python3, one option is to use str.translate.
First, use string methods - string.ascii_uppercase and string.ascii_lowercase to build strings with entire character sets 'A..Z' and 'a..z'. Use str.maketranslate to make a translation table, one for upper case letters to lower case and another for lower case to upper case letters. Finally, loop through the required string, and use str.translate to build the converted string.
import re
import string
test_str = r'The Tree outside is gREEN'
new_str = ''
str_lower = string.ascii_lowercase
#'abcdefghijklmnopqrstuvwxyz'
str_upper = string.ascii_uppercase
#'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
tr_to_upper = str.maketrans(str_lower, str_upper)
tr_to_lower = str.maketrans(str_upper, str_lower)
for char in test_str:
if re.findall(r'[A-Z]', char):
new_str = new_str + char.translate(tr_to_lower)
elif re.findall(r'[a-z]', char):
new_str = new_str + char.translate(tr_to_upper)
else:
new_str = new_str + char
print('{}'.format(new_str))
Output:
tHE tREE OUTSIDE IS Green
How about a cipher? It's not quite as readable but it seriously reduces the line count.
def swap_cases(data):#ONLY INTENDED FOR USE WITH ASCII! EBCDIC OR OTHER INTERCHANGE CODES MAY BE PROBLEMATIC!
output = list(data);
for i in range(0,len(data)):
if ord(output[i]) > 64 < 123: output[i] = chr(ord(data[i]) ^ ord(list(" "*70)[i % len(" "*70)]));
return "".join(output);
print(swap_cases(input("ENTRY::")))
No effecting special characters or anything not in the alphabet, 6 lines of code, relatively fast algorithm no external modules, doesn't use swap() or others string functions and contains only one if block, returning a string as requested not a list.
EDIT:
Come to think of it you can reduce a lot of the clutter by doing this:
if ord(output[i]) > 64 < 123: output[i] = chr(ord(data[i]) ^ 32);
instead of:
if ord(output[i]) > 64 < 123: output[i] = chr(ord(data[i]) ^ ord(list(" "*70)[i % len(" "*70)]));
I'm writing code so you can shift text two places along the alphabet: 'ab cd' should become 'cd ef'. I'm using Python 2 and this is what I got so far:
def shifttext(shift):
input=raw_input('Input text here: ')
data = list(input)
for i in data:
data[i] = chr((ord(i) + shift) % 26)
output = ''.join(data)
return output
shifttext(3)
I get the following error:
File "level1.py", line 9, in <module>
shifttext(3)
File "level1.py", line 5, in shifttext
data[i] = chr((ord(i) + shift) % 26)
TypError: list indices must be integers, not str
So I have to change the letter to numbers somehow? But I thought I already did that?
You are looping over the list of characters, and i is thus a character. You then try to store that back into data using the i character as an index. That won't work.
Use enumerate() to get indexes and the values:
def shifttext(shift):
input=raw_input('Input text here: ')
data = list(input)
for i, char in enumerate(data):
data[i] = chr((ord(char) + shift) % 26)
output = ''.join(data)
return output
You can simplify this with a generator expression:
def shifttext(shift):
input=raw_input('Input text here: ')
return ''.join(chr((ord(char) + shift) % 26) for char in input)
But now you'll note that your % 26 won't work; the ASCII codepoints start after 26:
>>> ord('a')
97
You'll need to use the ord('a') value to be able to use a modulus instead; subtracting puts your values in the range 0-25, and you add it again afterwards:
a = ord('a')
return ''.join(chr((ord(char) - a + shift) % 26) + a) for char in input)
but that will only work for lower-case letters; which might be fine, but you can force that by lowercasing the input:
a = ord('a')
return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in input.lower())
If we then move asking for the input out of the function to focus it on doing one job well, this becomes:
def shifttext(text, shift):
a = ord('a')
return ''.join(chr((ord(char) - a + shift) % 26 + a) for char in text.lower())
print shifttext(raw_input('Input text here: '), 3)
and using this on the interactive prompt I see:
>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Cesarsalad!
fhvduvdodgr
Of course, now punctuation is taken along. Last revision, now only shifting letters:
def shifttext(text, shift):
a = ord('a')
return ''.join(
chr((ord(char) - a + shift) % 26 + a) if 'a' <= char <= 'z' else char
for char in text.lower())
and we get:
>>> print shifttext(raw_input('Input text here: '), 3)
Input text here: Ceasarsalad!
fhdvduvdodg!
Looks you're doing cesar-cipher encryption, so you can try something like this:
strs = 'abcdefghijklmnopqrstuvwxyz' #use a string like this, instead of ord()
def shifttext(shift):
inp = raw_input('Input text here: ')
data = []
for i in inp: #iterate over the text not some list
if i.strip() and i in strs: # if the char is not a space ""
data.append(strs[(strs.index(i) + shift) % 26])
else:
data.append(i) #if space the simply append it to data
output = ''.join(data)
return output
output:
In [2]: shifttext(3)
Input text here: how are you?
Out[2]: 'krz duh brx?'
In [3]: shifttext(3)
Input text here: Fine.
Out[3]: 'Flqh.'
strs[(strs.index(i) + shift) % 26]: line above means find the index of the character i in strs and then add the shift value to it.Now, on the final value(index+shift) apply %26 to the get the shifted index. This shifted index when passed to strs[new_index] yields the desired shifted character.
Martijn's answer is great. Here is another way to achieve the same thing:
import string
def shifttext(text, shift):
shift %= 26 # optional, allows for |shift| > 26
alphabet = string.lowercase # 'abcdefghijklmnopqrstuvwxyz' (note: for Python 3, use string.ascii_lowercase instead)
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
return string.translate(text, string.maketrans(alphabet, shifted_alphabet))
print shifttext(raw_input('Input text here: '), 3)
It's easier to write a straight function shifttext(text, shift). If you want a prompt, use Python's interactive mode python -i shift.py
> shifttext('hello', 2)
'jgnnq'
Tried with Basic python.
may useful for someone.
# Caesar cipher
import sys
text = input("Enter your message: ")
cipher = ''
try:
number = int(input("Enter Number to shift the value : "))
except ValueError:
print("Entered number should be integer. please re0enter the value")
try:
number = int(input("Enter Number to shift the value : "))
except:
print("Error occurred. please try again.")
sys.exit(2)
for char in text:
if not char.isalpha():
flag = char
elif char.isupper():
code = ord(char) + number
if 64 < code <= 90:
flag = chr(code)
elif code > 90:
flag = chr((code - 90) + 64)
elif char.islower():
code = ord(char) + number
if 96 < code <= 122:
flag = chr(code)
elif code > 122:
flag = chr((code - 122) + 96)
else:
print("not supported value by ASCII")
cipher += flag
print(cipher)