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")
Related
input: ['baNaNa', 7] # string and step size
required output : 'utGtGt' # every character of string shifted backwards by step size
import ast
in_string = input()
lis = ast.literal_eval(in_string)
st = lis[0]
step = lis[1]
alphabets = 'abcdefghijklmnopqrstuvwxyz'
password = ''
for letter in st:
if letter in alphabets:
index_val = alphabets.index(letter) - (step)
password += alphabets[index_val]
print(password)
Output i am getting is 'utgtgt'. I want 'utGtGt'. Help on this would be appreciated a lot.
The string module has methods to create a transformation dictionary and a translate method to do exactly what you want:
st = "baNaNa"
step = 7
alphabets = 'abcdefghijklmnopqrstuvwxyz'
alph2 = alphabets.upper()
# lower case translation table
t = str.maketrans(alphabets, alphabets[-step:]+alphabets[:-step])
# upper case translation table
t2 = str.maketrans(alph2, alph2[-step:]+alph2[:-step])
# merge both translation tables
t.update(t2)
print(st.translate(t))
Output:
utGtGt
You give it the original string and an equal long string to map letters to and apply that dictionary using str.translate(dictionary).
The sliced strings equate to:
print(alphabets)
print(alphabets[-step:]+alphabets[:-step])
abcdefghijklmnopqrstuvwxyz
tuvwxyzabcdefghijklmnopqrs
which is what your step is for.
See Understanding slice notation if you never saw string slicing in use.
by processing each charater and checking it's cardinal no and making calculation accordingly help you to reach the result
def func(string, size):
if size%26==0:
size=26
else:
size=size%26
new_str = ''
for char in string:
if char.isupper():
if ord(char)-size<ord('A'):
new_str+=chr(ord(char)-size+26)
else:
new_str+=chr(ord(char)-size)
elif char.islower():
if ord(char)-size<ord('a'):
new_str+=chr(ord(char)-size+26)
else:
new_str+=chr(ord(char)-size)
return new_str
res =func('baNaNa', 7)
print(res)
# output utGtGt
Here's a simple solution that makes use of the % modulo operator to shift letters backwards.
It basically collects all of the letters in a reverse index lookup dictionary, so looking up letter positions is O(1) instead of using list.index(), which is linear O(N) lookups.
Then it goes through each letter and calculates the shift value from the letter index e.g. for the letter a with a shift value of 7, the calculation will be (0 - 7) % 26, which will give 19, the position of u.
Then once you have this shift value, convert it to uppercase or lowercase depending on the case of the original letter.
At the end we just str.join() the result list into one string. This is more efficient than doing += to join strings.
Demo:
from string import ascii_lowercase
def letter_backwards_shift(word, shift):
letter_lookups = {letter: idx for idx, letter in enumerate(ascii_lowercase)}
alphabet = list(letter_lookups)
result = []
for letter in word:
idx = letter_lookups[letter.lower()]
shifted_letter = alphabet[(idx - shift) % len(alphabet)]
if letter.isupper():
result.append(shifted_letter.upper())
else:
result.append(shifted_letter.lower())
return ''.join(result)
Output:
>>> letter_backwards_shift('baNaNa', 7)
utGtGt
I would probably go with #Patrick Artner's pythonic solution. I just showed the above implementation as a learning exercise :-).
Write a function that accepts a string and a character as input and
returns the count of all the words in the string which start with the
given character. Assume that capitalization does not matter here. You
can assume that the input string is a sentence i.e. words are
separated by spaces and consists of alphabetic characters.
This is my code:
def count_input_character (input_str, character):
input_str = input_str.lower()
character = character.lower()
count = 0
for i in range (0, len(input_str)):
if (input_str[i] == character and input_str[i - 1] == " "):
count += 1
return (count)
#Main Program
input_str = input("Enter a string: ")
character = input("Enter character whose occurances are to be found in the given input string: ")
result = count_input_character(input_str, character)
#print(result)
The only part missing here is that how to check if the first word of the sentence is stating with the user given character. consider this output:
Your answer is NOT CORRECT Your code was tested with different inputs. > For example when your function is called as shown below:
count_input_character ('the brahman the master of the universe', 't')
####### Your function returns ############# 2 The returned variable type is: type 'int'
### Correct return value should be ######## 3 The returned variable type is: type 'int'
You function misses the first t because in this line
if (input_str[i] == character and input_str[i - 1] == " "):
when i is 0, then input_str[i - 1] is input_str[-1] which Python will resolve as the last character of the string!
To fix this, you could change your condition to
if input_str[i] == character and (i == 0 or input_str[i - 1] == " "):
Or use str.split with a list comprehension. Or a regular expression like r'(?i)\b%s', with (?i) meaning "ignore case", \b is word boundary and %s a placeholder for the character..
Instead of looking for spaces, you could split input_str on whitespace, this would produce a list of words that you could then test against character. (Pseudocode below)
function F sentence, character {
l = <sentence split by whitespace>
count = 0
for word in l {
if firstchar(word) == character {
count = count + 1
}
}
return count
}
Although it doesn't fix your specific bug, for educational purposes, please note you could rewrite your function like this using list comprehension:
def count_input_character (input_str, character):
return len([x for x in input_str.lower().split() if x.startswith(character.lower())])
or even more efficiently(thanks to tobias_k)
def count_input_character (input_str, character):
sum(w.startswith(character.lower()) for w in input_str.lower().split())
def c_upper(text, char):
text = text.title() #set leading char of words to uppercase
char = char.upper() #set given char to uppercase
k = 0 #counter
for i in text:
if i.istitle() and i == char: #checking conditions for problem, where i is a char in a given string
k = k + 1
return k
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)]));
My code suppose to take a string to a function and then switch the caps of each char in there from h to H and E to e
but I somewhat get an error in my if s
why is that?
This is the error messege:
chr = str[i]
TypeError: string indices must be integers, not str
My code is:
def CapsChanger(str):
i = str[0]
for i in str :
chr = str[i]
if((ord(chr) > 46) and (ord(chr) < 91)):
str[i].upper()
if((ord(chr) > 96) and (ord(chr) < 126)):
str[i].lower()
print str
str = raw_input()
CapsChanger(str)
input()
When you do for i in str, in each iteration i represents that actual character, not the index. So you don't need to do chr = str[i] - i is already that character.
import string
def invertCase(text):
## Creating a list where results will be stored
results = list()
## This will contain the abc in upper and lowercase: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abc = string.lowercase + string.uppercase
## Looping each letter of the received text
for letter in text:
## If the current letter of the loop exists in our abc variable contents, it means it's a letter and not a symbol or space
## So we can apply upper() or lower() to the letter.
if letter in abc:
## If the letter is currently uppercase, then we turn it into lowercase
if letter.isupper():
results.append(letter.lower())
## If the letter is currently lowercase, then we turn it into uppercase
else:
results.append(letter.upper())
## The current letter of the loop is not in our abc variable so it could be anything but a letter
## So we just append it to our results list
else:
results.append(letter)
## Once the loop finishes we just join every item in the list to make the final string and return it
return ''.join(results)
print invertCase('SoMeOnE Is hAvING fUN')
Output:
sOmEoNe iS HaVing Fun
The variable i is already a 1 character string because the for loop processes strings this way. Also, when you call str[i].upper(), it needs to either be assigned to something, or printed out, otherwise the character is never actually changed in place. .lower() and .upper() also have a behaviour which already checks the range for you, and returns the same characters. Eg. if it already uppercase, or a number, upper() will just return the same character.
Your function can be simplified as follows:
import sys
def CapsChanger(str):
for i in str:
sys.stdout.write (i.lower() if (i.upper() == i) else i.upper())
print
str = raw_input()
CapsChanger(str)
sys.stdout.write is used to avoid printing out extra spaces. The ternary operator is used to switch case in one shot:
<value1> if <condition> else <value2>
i is a string, not index. If You need index use enumerate:
for idx, i in str:
print idx, i
Insted of ord(chr) use string that represent a letter.
Insted of two if conditions use Chained Comparisons.
def CapsChanger(str):
out = []
for idx,chr in enumerate(str):
if 'Z' >= chr >= 'A':
out.append(chr.lower())
elif 'z' >= chr >= 'a':
out.append(chr.upper())
print(''.join(out))
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