converting individual characters in string to uppercase - python-3.x

my code
name='helloworld'
i=0
while(i<len(name)):
name[i].upper()
i=i+2
print(i)
print(name)
want the output as 'AnThRoPoMoRpHiSm'. Please help.

You can enumerate your string and capitalize one of every 2 letters, then join the result:
name='anthropomorphism'
''.join([s if i%2 else s.upper() for i,s in enumerate(name)])
This returns:
'AnThRoPoMoRpHiSm'

Related

Write a function that removes all occurrences of a given letter from a string [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 3 years ago.
Write a function that removes all occurrences of a given letter from a string:
remove_letter("a", "apple") == "pple"
remove_letter("a", "banana") == "bnn"
remove_letter("z", "banana") == "banana"
I have tried to make a list from the string and then deleting the element. Below is my code for this problem. Is this correct? Or should I think of something else? Can you tell a better method than this and why is that method better?
def rmv(word, letter):
word = list(word)
for ele in word:
if ele == letter:
word.remove(ele)
print(word)
This code does not show any error messages. It gives the expected output for the words like "banana" but for word like "bananna" it would not give the expected output.
For rmv("banana", "n") output is "baaa".
For rmv("bananna", "n") output is "baana".
Your code approach with fix:
def rmv(word, letter):
word = list(word)
newWord=[]
for i in range(len(word)):
if word[i]!= letter:
newWord.append(word[i])
print(newWord)
rmv("bananna", "n")
What you were doing wrong:
You were iterating your list and deleting as and when your if-else met the condition:
if ele == letter:
word.remove(ele)
But the problem with this approach is that your pointer moves ahead and the deletion causes the list to shift accordingly at the same time and so when you see the case of
rmv("bananna", "n")
By the time pointer could get the opportunity to scan and remove the last n the list caused it to shift at an index that was already scanned by your list and hence it got ignored.
On a side note -
I generally advise people to use Python-tutor to debug their code. It's GUI based code visualizations helps to know where you went wrong.
Your problem is that you modify (remove) a list while you iterate over it. Just put a few print lines into your code to see what it does.
It's better to create a new list and adding only characters that you want to keep:
def rmv(word, letter):
out = []
for char in word:
if char != letter:
out.append(char)
return ''.join(out)
or, even more compactly:
def rmv(word, letter):
return ''.join(char for char in word if char != letter)
Why not just:
def rmv(word, letter):
return word.replace(letter, '')
print(rmv("apple", "a"))
There is no need for you to iterate through each character of the string when one function call will do it for you.
Why don't you try the string replace function?
Try this code:
def rmv(word, letter):
return word.replace(letter, "")

Python3 reversing an inputed sentence

I am trying to create a function that reverses a sentence that a user inputs but when I run the program I am not getting the sentence in reverse. Bellow is my code
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=sentence.split()
newsentence=words.reverse()
return (newsentence)
print(sentence_reverse(sentence))
def sentence_reverse(s):
return ' '.join(s.split()[::-1])
print(sentence_reverse(sentence))
you can do this
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
or :
def reverse2(s):
return s[::-1]
reverse() is an in-place operation, meaning it reverses words itself and doesnt return anything. So instead of returning newsentence, you want to return words like so:
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=sentence.split()
words.reverse()
return words
print(sentence_reverse(sentence))
>>>Enter a sentence: hello world
>>>['world', 'hello']
Here is a simplest way to solve your problem:
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words= sentence.split() # breaks the sentence into words
rev_sentence= ''
for word in words:
rev_sentence = ' ' + word + rev_sentence
return rev_sentence
print(sentence_reverse(sentence))
Input: Hi please reverse me
Ouput: me reverse please Hi
Hope this helps you. Kindly let me know if anything else is needed.
Welcome to StackOverflow!
The reason is because you are using split() but it does not convert your input string into the list of its character. It just make a list with one element, which is your input string. Instead, convert the string to list using list() function, and then convert it back to string using join() function. In addition to that, reverse() returns nothing. So, you have to returns the words variable instead.
sentence=input('Enter a sentence: ')
def sentence_reverse(sentence):
words=list(sentence)
words.reverse()
return ''.join(words)
print(sentence_reverse(sentence))

Function for removing vowels from a character

Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed.
For example, anti_vowel("Hey You!") should return "Hy Y!". Don't count Y as a vowel. Make sure to remove lowercase and uppercase vowels.
def anti_vowel(text):
b=""
for i in text:
print i
for j in "aeiouAEIOU":
if i!=j:
b+=i
break
return b
what am I doing wrong?
You should check using in.
If i not in "aeiouAEIOU":

Max Length Removal

The problem is If there is “100” as a sub-string in the string, then we can delete this sub-string. The task is to find the length of longest sub-string which can be make removed?
s=input('')
i=0
if '100' not in s:
print('0')
else:
st=''
while i<len(s)-2:
if s[i:i+3]=='100':
s= s.replace('100','')
a=s.find('100')
if a<=i:
st=st+'100'
i=a
else:
st='100'
i=i+1
else:
i=i+1
print(len(st))
for the input: 101001010000,this code is printing 9 instead of 12,
somehow the else part is not getting executed..
please someone help me out
s.replace() removes all occurrences of the substring, not just the first, and searching from the start.
This means that '101001010000'.replace('100', '') replaces two occurrences:
>>> '101001010000'.replace('100', '')
'101000'
but you count that as one replacement.
str.replace() takes a third argument, the number of replacements to be made, see the documentation:
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Use that to limit the number of replacements.

How can I delete the letter that occurs in the two strings using python?

That's the source code:
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
if str_one[i] == str_two[j]:
str_one = (str_one - str_one[i]).split()
print(str_one)
else:
print('There is no relation')
if __name__ == '__main__':
str_one = input('Put your First String: ').split()
str_two = input('Put your Second String: ')
print(revers_e(str_one, str_two))
How can I remove a letter that occurs in both strings from the first string then print it?
How about a simple pythonic way of doing it
def revers_e(s1, s2):
print(*[i for i in s1 if i in s2]) # Print all characters to be deleted from s1
s1 = ''.join([i for i in s1 if i not in s2]) # Delete them from s1
This answer says, "Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings."
First of all you don't need to use a pretty suboptimal way using range and len to iterate over a string since strings are iterable you can just iterate over them with a simple loop.
And for finding intersection within 2 string you can use set.intersection which returns all the common characters in both string and then use str.translate to remove your common characters
intersect=set(str_one).intersection(str_two)
trans_table = dict.fromkeys(map(ord, intersect), None)
str_one.translate(trans_table)
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
try:
if str_one[i] == str_two[j]:
first_part=str_one[0:i]
second_part=str_one[i+1:]
str_one =first_part+second_part
print(str_one)
else:
print('There is no relation')
except IndexError:
return
str_one = input('Put your First String: ')
str_two = input('Put your Second String: ')
revers_e(str_one, str_two)
I've modified your code, taking out a few bits and adding a few more.
str_one = input('Put your First String: ').split()
I removed the .split(), because all this would do is create a list of length 1, so in your loop, you'd be comparing the entire string of the first string to one letter of the second string.
str_one = (str_one - str_one[i]).split()
You can't remove a character from a string like this in Python, so I split the string into parts (you could also convert them into lists like I did in my other code which I deleted) whereby all the characters up to the last character before the matching character are included, followed by all the characters after the matching character, which are then appended into one string.
I used exception statements, because the first loop will use the original length, but this is subject to change, so could result in errors.
Lastly, I just called the function instead of printing it too, because all that does is return a None type.
These work in Python 2.7+ and Python 3
Given:
>>> s1='abcdefg'
>>> s2='efghijk'
You can use a set:
>>> set(s1).intersection(s2)
{'f', 'e', 'g'}
Then use that set in maketrans to make a translation table to None to delete those characters:
>>> s1.translate(str.maketrans({e:None for e in set(s1).intersection(s2)}))
'abcd'
Or use list comprehension:
>>> ''.join([e for e in s1 if e in s2])
'efg'
And a regex to produce a new string without the common characters:
>>> re.sub(''.join([e for e in s1 if e in s2]), '', s1)
'abcd'

Resources