Replace second occurence of every character in a string, Python - python

I want to replace every second occurence of a character from only a string as input. Using only the .replace method.
For example:
input: asdasdasdasd
output should be: asdASDasdasd
def main(string):
for char in string:
string.replace(char, char.upper())
return string
Im relatively new to Python and I can't wrap my head around what to do.

Alternatively, you can use a dictionary and make the second occurrence of each character to uppercase:
def upper_case_second_occurrence(s):
d = {}
s = list(s)
for i, c in enumerate(s):
d[c] = d.get(c, 0) + 1
if d[c] == 2:
s[i] = c.upper()
return "".join(s)
if __name__ == "__main__":
print(upper_case_second_occurrence("aaa"))
print(upper_case_second_occurrence("aaaaaa"))
print(upper_case_second_occurrence("asdasdasdasd"))
Output:
aAa
aAaaaa
asdASDasdasd

Try this one:
def main(s):
l = []
string = ''
y = True
for a in s:
if a in l and y:
string+=a.upper()
l.remove(a)
if not len(l):
l = ''
continue
try:
l.append(a)
except AttributeError:
y = False
string+=a
return(string)
print(main('asdasdasdasd')) # → asdASDasdasd
print(main('aaa')) # → aAa
print(main('aaaaa')) # → aAaaa
print(main('AAA') # → AAA

Try using .count():
def main(string):
new_string = ''
for char in string:
if new_string.lower().count(char) == 1: # This line checks if the count of char is 1 or not. If yes, then it appends the uppercase letter of char
new_string += char.upper()
else:
new_string += char
return new_string
Output:
main('asdasdasdasd')
'asdASDasdasd'
main('aaaaaa')
'aAaaaa'
main('aaa')
'aAa'

Related

Write a program that changes to letters given in an array to '* "in a given string

Write a function that changes letters given in an array to '*' in a given string.
'Irisk' ['i','k'] -> *r * s *
I have tried using:
def filter(word, lett):
new_word = ''
for c in word:
if c == lett:
new_word += '*'
else:
new_word += c
return new_word
You can use a loop to go with "*" or the original letter if the letter is in a list.
Then combine the characters using ''.join().
Like this:
my_string = 'Irisk'
my_list = ['i', 'k']
new_string = ''.join("*" if (c.lower() in my_list) else c for c in my_string)
Result:
'*r*s*'
use 'in' instead of ==
def filter(word, lett):
new_word = ""
for c in word:
if c in lett:
new_word += "*"
else:
new_word += c
return new_word
Just use python's built-in String.replace method:
def filter(word, letter):
return word.replace(letter, "*")
Make use of Python builtin string functions - replace
def filter(s: str, c: list) -> str:
n = s
for i in c:
n = n.replace(i, '*')
return n
Convert both word and lett to lower case when comparing them.
def filter(word, lett):
new_word = ""
for c in word.lower():
if c in "".join(lett).lower():
new_word += "*"
else:
new_word += c
return new_word
print(filter("Irisk" ,['i','k']))
Output:
*r*s*

Int and str changing every letter with error + EDIT: zero indexing eachword

My goal is to write a function which change every even letter into upper letter and odd to lower (space also count as a one element).
This is my code
def to_weird_case(s):
for i in s:
if len(i) % 2 == 0:
s[i] = i.upper() + s(i+1)
else:
s[i] = i.lower() + s(i+2)
return i
I think it should be quite correct, but it gives me error.
line 7, in to_weird_case
s[i] = i.lower() + s(str(i)+2)
TypeError: must be str, not int
EDIT:
I have a sugesstion but I don't know how to make it. I try it for myself and back here.
This needs to definitly explicietly state that the zero indexing uppercase is for each word.
Do you know guys how to make it?
So we can analyze your code and just explain what you typed:
def to_weird_case(s):
for i in s: # s is your string, and i is the actual character
if len(i) % 2 == 0: # if your length of the character can be divided by 2. Hmm this is weird
s[i] = i.upper() + s(i+1) # s[i] change a character in the string but you should provide an index (i) so an integer and not a character. But this is not supported in Python.
else:
s[i] = i.lower() + s(i+2)
return i # This will exit after first iteraction, so to_weird_case("this") will return "t".
So what you need to is first create a output string and fill that. And when iteration over s, you want the index of the char and the char value itself.
def to_weird_case(s):
output = ""
for i, myChar in enumerate(s):
if i % 2 == 0:
output += myChar.upper()
else:
output += myChar.lower()
return output
my_sentence = "abcdef"
print(to_weird_case(my_sentence))
And when you want to ignore spaces, you need to keep track of actual characters (excluding spaces)
def to_weird_case(s):
output = ""
count = 0
for myChar in s:
if myChar.isspace():
output += myChar
else:
if count % 2 == 0:
output += myChar.upper()
else:
output += myChar.lower()
count += 1
return output
my_sentence = "abc def"
print(to_weird_case(my_sentence))
Test this yourself
def to_weird_case(s):
for i in s:
print (i)
After doing this you will find that i gives you characters.
if len(i) % 2 == 0:
This line is incorrect as you are trying to find the length of a single character. len(s) would be much better.
So the code will be like
def to_weird_case(s):
s2 = "" #We create another string as strings are immutable in python
for i in range(len(s)):
if i % 2 == 0:
s2 = s2 + s[i].upper()
else:
s2 = s2 + s[i].lower()
return s2
From #RvdK analysis, you'ld have seen where corrections are needed. In addition to what has been pointed out, I want you to note that s[i] will work fine only if i is an integer, but in your case where (by assumption) i is a string you'll encounter several TypeErrors. From my understanding of what you want to do, it should go this way:
def to_weird_case(s):
for i in s:
if s.index(i) % 2 == 0:
s[s.index(i)] = i.upper() + s[s.index(i)]
elif s.index(i) % 2 == 1:
s[s.index(i)] = i.lower() + s[s.index(i)]
return i # or possibly return s
It is possible to do in a single line using a list comprehension
def funny_case(s):
return "".join([c.upper() if idx%2==0 else c.lower() for idx,c in enumerate(s)])
If you want to treat each word separately then you can split it up in to a list of words and "funny case" each word individually, see below code
original = "hello world"
def funny_case(s):
return "".join([c.upper() if idx%2==0 else c.lower() for idx,c in enumerate(s) ])
def funny_case_by_word(s):
return " ".join((funny_case(word) for word in s.split()))
print(funny_case_by_word(original))
Corrected code is as follows
def case(s):
txt=''
for i in range(len(s)):
if i%2==0:
txt+=s[i].upper()
else:
txt+=s[i].lower()
return txt
String assignment gives error in Python therefore i recommend considering my approach
When looping over elements of s, you get the letter itself, not its index. You can use enumerate to get both index and letter.
def to_weird_case(s):
result = ''
for index, letter in enumerate(s):
if index % 2 == 0:
result += letter.upper()
else:
result += letter.lower()
return result
correct code:
def to_weird_case(s):
str2 = ""
s.split() # through splitting string is converted to list as it is easy to traverse through list
for i in range(0,len(s)):
n = s[i] # storing value in n
if(i % 2 == 0):
str2 = str2 + n.upper()
else:
str2 = str2 + n.lower()
return str2
str1 = "hello world"
r = to_weird_case(str1)
print(r)

How to capitalize 1st and 4th characters of a string?

OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name
I'm trying to write this in different ways and I also feel like there's an easier way to do this. Cant, you directly apply it without getting all the other words of a string? Or a split or something?
Here is one of my attempts at trying it another way. I'm trying to do it with a for AND an if statement too. Any help is appreciated.
def old_macdonald(words):
wordletter = words[0]
fourthletter = words[3]
newword = []
for i,l in enumerate(words):
if i[0]:
newword = l.capatalize
return newword
if i[3]:
newword = l.capatalize
return newword
This is the most legible way IMO
def old_macdonald(name):
mylist = list(name)
mylist[0] = mylist[0].upper()
mylist[3] = mylist[3].upper()
return ''.join(mylist)
def old_macdonald(name):
letters = list(name)
for index in range(len(name)):
if index == 0:
letters[index] = letters[index].upper()
elif index == 3:
letters[index] = letters[index].upper()
return "".join(letters)
This one worked for me
this code will make first and forth element of the string Capital.
def cap(name):
first = name[0]
mid = name[1:3]
second = name[3]
rest = name[4:]
return first.upper() + mid + second.upper() + rest
cap('kahasdfn')
Here's one way. You do need to split the string into a list of characters to change individual characters, because strings are immutable, and then use join afterward to convert them back into a string.
def old_macdonald(name):
letters = list(name)
for letter_to_capitalize in [1, 4]:
if len(letters) >= letter_to_capitalize:
letters[letter_to_capitalize - 1] = letters[letter_to_capitalize - 1].upper()
return "".join(letters)
A pretty simple and modifiable example.
def old_mcdonald(word):
indexes = (0,3) #letters i want to cap
new_word = "".join([v.capitalize() if i in indexes else v for i,v in enumerate(word)])
return new_word
def old_macdonald(s):
return ''.join([s[:1].upper(), s[1:3], s[3:4].upper(), s[4:]])
# s[:1] - letter index 0 (first)
# s[1:3] - letters index 1-2
# s[3:4] - letter index 3 (fourth)
# s[4:] - letters index 4 onward
test_string = "abcdefghijklmnopqr"
print(old_macdonald(test_string )) # AbcDefghijklmnopqr
I like writing it this way:
def old_macdonald(word):
indices = (0, 4)
return ''.join(c.capitalize() if index in indices else c for index, c in enumerate(word))
Although it's a little long, so you might prefer writing it more clearly as:
def old_macdonald(word):
indices = (0, 4)
new_string = []
for index, c in enumerate(word):
new_string.append(c.capitalize() if index in indices else c)
return ''.join(new_string)
def old_macdonald(s):
w=""
for i in s:
t=s.index(i)
if t==0:
w=w+i.upper()
elif(t==3):
w=w+i.upper()
else:
w=w+i
print(w)
old_macdonald("aman")
def old_macdonald(s):
return s[0:3].capitalize() + s[3:].capitalize()
https://ideone.com/2D0qbZ
This one worked
def old_macdonald(name):
word = ''
for index,letter in enumerate(name):
if index == 0 or index == 3:
letter = name[index].capitalize()
word += letter
else:
word += letter
return word

Letter Change using Python

Problem statement:
Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
My Python program is:
def LetterChanges(str):
for i in range(0,len(str)):
a=ord(str[i])
if a==122:
str=str.replace(str[i],'a',1)
elif a==90:
str=str.replace(str[i],'a',1)
elif (a>=65 and a<=90) or (a>=97 and a<=122):
a=a+1
char=chr(a)
str=str.replace(str[i],char,1)
for i in range(0,len(str)):
if str[i]=='a':
str=str.replace(str[i],'A',1)
elif str[i]=='e':
str=str.replace(str[i],'E',1)
elif str[i]=='i':
str=str.replace(str[i],'I',1)
elif str[i]=='o':
str=str.replace(str[i],'O',1)
elif str[i]=='u':
str=str.replace(str[i],'U',1)
return(str)
print LetterChanges(raw_input())
The problem with my code is that, when I input sen, the output was tfo which was correct.
But when I gave sent as my input, I got the wrong output.
Your mistake is here :silpa
when you are replacing you have not cared about indices where character is replacing so how it is going when you give sent input
after replacing n we get string like tfot now in next iteration next letter you encounter in your original string is t so it will replace the first letter that is t in the replaced string so . "tfot" becomes "ufot" and last t is not being replaced
here an another try :
def prgrm(n):
k = ""
for i in n:
nxt = chr(97 if i == 'z' else ord(i)+1)
if nxt in ('a', 'e', 'i', 'o', 'u'):
nxt = nxt.capitalize()
k += nxt
print(k)
prgrm('sen')
A functional programming take, without using ord() or a loop, will work with presence of other non alphabetic characters I think:
def LetterChanges(str):
vowels = "aeiou"
lowers = "abcdefghijklmnopqrstuvwxyza"
all = lowers.upper() + lowers
# Map all alphabetical characters
nxt_str = "".join(map(lambda x: all[all.index(x) + 1] if x in all else x, str))
# Map the vowels
return "".join(map(lambda x: x.upper() if x in vowels else x, nxt_str))
print(LetterChanges("sentdZ"))
tfOUEA
You are processing the 't' twice in your string, first the s is replaced by 't' and after that 't' is replaced again by 'u' also the first replacement in the string
def LetterChanges(line):
result = ""
for i in line:
a=ord(i)
if a == 122 or a == 90:
result += 'A'
elif (a >= 65 and a <= 90) or (a >= 97 and a <= 122):
a = a + 1
char = chr(a)
if char in ('e', 'i', 'o', 'u'):
char = char.upper()
result += char
else:
result += i
return(result)
Here is another way with using re:
import re
def letter_changes(my_string):
in_letters = "abcdefghijklmnopqrstuvxyz"
out_letters = "bcdefghijklmnopqrstuvxyza"
letter_dict1 = {x:y for x,y in zip(in_letters, out_letters)}
letter_dict2 = {'a':'A', 'e':'E', 'i':'I', 'o':'O', 'u':'U'}
for l_dict in [letter_dict1, letter_dict2]:
pattern = re.compile("|".join(l_dict.keys()))
my_string = pattern.sub(lambda m: l_dict[re.escape(m.group(0))], my_string)
return my_string
This is another way to write your code:-
def rep_cap(sent):
sent_rp = ''.join([chr(c) for c in [x+1 for x in [ord(c) for c in sent]]]).replace('{','a') #This thing is done to convert a to b .... z to a
final_output = ""
vowels = ['a','e','i','o','u']
for i in sent_rp:
if i in vowels:
final_output = final_output+i.upper() #convert vowels to upper case
else :
final_output = final_output+i
return final_output
sent = raw_input("Enter a sentence:")
print rep_cap(sent)
replace this line
str=str.replace(str[i],char,1) with
str = str[:i] + char + str[i+1:]
Reason for this problem answered by #Pankaj78691 is correct!!
Here is my version of the algorithm.
def LetterChanges(str):
result = ''
vowels = ['a','e','i','o','u']
for s in str:
if s.isalpha():
if ord(s) == 122: #ASCII code of 'z'
next_letter = chr(97)
else:
next_letter = chr(ord(s)+1)
if next_letter in vowels:
result += next_letter.upper()
else:
result += next_letter
else:
result += s
return result

how can I convert a2c3d to accfd?

here we just have to add the num written to the previous character ascii value .
I tried that
if __name__ == '__main__':
n = input()
list1 = list(n)
for i in list1:
if list1[i] is not chr:
list1[i] = list1[i-1] + list1[i]
print(list(n))
This approach has the advantage to not use a list. It stores the previous char in the prev variable to use in case of a digit.
text = 'a2c3d'
result = ''
prev = None
for ch in text:
if ch.isdigit() and prev:
result += chr(int(ch) + ord(prev))
else:
result += ch
prev = ch
print(result)
You iterate the given string, if it is a character you add it to a list. if not you take the ord() of the last char in your list and add the number. you stick all together at the end:
def change(t):
rv = [] # accumulates all characters
for c in t: # iterate all characters in t
if c.isdigit(): # if a digit
if not rv: # and no characters in rv: error
raise ValueError("Cant have number before character")
rv.append(chr(ord(rv[-1])+int(c))) # else append the number to the last char
else:
rv.append(c) # not a number, simply append
return ''.join(rv) # join all characters again
print(change("a2c3d"))
Output:
accfd

Categories