Uppercase the second letter of each word in Python - python

Trying to solve a simple problem that seems to have a difficult answer. The problem is uppercase the second letter of each word in Python. I thought I had the code right, but it seems that its returning only the last word in the split.
What am I doing wrong?
def capitalize_n(s, n):
result = ""
for word in s.split():
result = word[:n].lower() + word[n:].capitalize()
return result
capitalize_n('hello world', 1)
output
wOrld

Does that do what you wanted?
def capitalize_n(s, n):
return " ".join(word[:n] + word[n:].capitalize() for word in s.split())
print(capitalize_n('hello world', 1))
The result is hEllo wOrld.
What you did wrong that is in each iteration you re-assigned to the variable result using the = operator instead of adding to that using the += operator.

Do this. You are always assigning But you should concatenate with previous also create a space.
def capitalize_n(s, n):
result = ""
for word in s.split():
result += word[:n].lower() + word[n:].capitalize() + " "
return result
capitalize_n('hello world', 1)

to modify your code, add += instead of = ,
then fix for space
def capitalize_n(s, n):
result = ""
for word in s.split():
result += word[:n].lower() + word[n:].capitalize() + ' '
return result
capitalize_n('hello world', 1).strip()
output:
'hEllo wOrld'

Related

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)

Not converting letters to uppercase and lowercase in python

I'm trying to make a program that will convert any text into a different form. That means that a text such as 'hi there' becomes 'hI tHeRe'.
list = []
word = input('Enter in a word or a sentence! ')
for num in range(len(word)):
list.clear()
list.append('i')
letter = word[num]
for x in range(len(list)):
if x % 2 == 0:
i = word.index(letter)
place = letter.lower()
word = word.replace(word[i], place)
if not x % 2 == 0:
i = word.index(letter)
place = letter.upper()
word = word.replace(word[i], place)
print(word)
However, when I run the code it just prints the same string as normal.
When using replace, you have to assign the result to your variable:
word = word.replace(word[i], place)
However, replace is actually not what you want here. replace replaces all instances of a certain pattern with a new string. In your current code, every instance of whatever letter word[i] represents will be replaced with the result of .lower() or .upper().
You also don't want to use the word list, since doing so will shadow the Python built-in list class.
If you want to keep most of your original logic, you can follow #khelwood's suggestion in the comments and end up with the following:
word = input('Enter in a word or a sentence! ')
wordList = list(word)
for i in range(len(word)):
if i % 2 == 0:
wordList[i] = word[i].lower()
else:
wordList[i] = word[i].upper()
print(''.join(wordList))
Here is one of my previous codes, you can change all the variable names to whatever you see fit.
s = input('Enter in a word or string.')
ret = ""
i = True # capitalize
for char in s:
if i:
ret += char.upper()
else:
ret += char.lower()
if char != ' ':
i = not i
print(ret)
I hope it works for you.
Try this one liner -
a = 'hi there'
''.join([i[1].lower() if i[0]%2==0 else i[1].upper() for i in enumerate(a)])
'hI ThErE'
If you care about each word starting from lowercase then this nested list comprehension works -
' '.join([''.join([j[1].lower() if j[0]%2==0 else j[1].upper() for j in enumerate(i)]) for i in a.split()])
'hI tHeRe'
The problem is with list.clear in the beginning of the for loop.
Each iteration you clear the list so the second for iteration run on the first item only.
Remove list.clear and it should scan the input word

Python iterations mischaracterizes string value

For this problem, I am given strings ThatAreLikeThis where there are no spaces between words and the 1st letter of each word is capitalized. My task is to lowercase each capital letter and add spaces between words. The following is my code. What I'm doing there is using a while loop nested inside a for-loop. I've turned the string into a list and check if the capital letter is the 1st letter or not. If so, all I do is make the letter lowercase and if it isn't the first letter, I do the same thing but insert a space before it.
def amendTheSentence(s):
s_list = list(s)
for i in range(len(s_list)):
while(s_list[i].isupper()):
if (i == 0):
s_list[i].lower()
else:
s_list.insert(i-1, " ")
s_list[i].lower()
return ''.join(s_list)
However, for the test case, this is the behavior:
Input: s: "CodesignalIsAwesome"
Output: undefined
Expected Output: "codesignal is awesome"
Console Output: Empty
You can use re.sub for this:
re.sub(r'(?<!\b)([A-Z])', ' \\1', s)
Code:
import re
def amendTheSentence(s):
return re.sub(r'(?<!\b)([A-Z])', ' \\1', s).lower()
On run:
>>> amendTheSentence('GoForPhone')
go for phone
Try this:
def amendTheSentence(s):
start = 0
string = ""
for i in range(1, len(s)):
if s[i].isupper():
string += (s[start:i] + " ")
start = i
string += s[start:]
return string.lower()
print(amendTheSentence("CodesignalIsAwesome"))
print(amendTheSentence("ThatAreLikeThis"))
Output:
codesignal is awesome
that are like this
def amendTheSentence(s):
new_sentence=''
for char in s:
if char.isupper():
new_sentence=new_sentence + ' ' + char.lower()
else:
new_sentence=new_sentence + char
return new_sentence
new_sentence=amendTheSentence("CodesignalIsAwesome")
print (new_sentence)
result is codesignal is awesome

Python How to capitalize nth letter of a string

I tried this: Capitalize a string. Can anybody provide a simple script/snippet for guideline?
Python documentation has capitalize() function which makes first letter capital. I want something like make_nth_letter_cap(str, n).
Capitalize n-th character and lowercase the rest as capitalize() does:
def capitalize_nth(s, n):
return s[:n].lower() + s[n:].capitalize()
my_string[:n] + my_string[n].upper() + my_string[n + 1:]
Or a more efficient version that isn't a Schlemiel the Painter's algorithm:
''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]])
x = "string"
y = x[:3] + x[3].swapcase() + x[4:]
Output
strIng
Code
Keep in mind that swapcase will invert the case whether it is lower or upper.
I used this just to show an alternate way.
This is the comprehensive solution: either you input a single word, a single line sentence or a multi line sentence, the nth letter will be converted to Capital letter and you will get back the converted string as output:
You can use this code:
def nth_letter_uppercase(string,n):
listofwords = string.split()
sentence_upper = ''
for word in listofwords:
length = len(word)
if length > (n - 1):
new_word = word[:n-1] + word[n-1].upper() + word[n:]
else:
new_word = word
sentence_upper += ' ' + new_word
return sentence_upper
calling the function defined above (I want to convert 2nd letter of each word to a capital letter):
string = '''nature is beautiful
and i love python'''
nth_letter_uppercase(string,2)
output will be:
'nAture iS bEautiful aNd i lOve pYthon'
I know it's an old topic but this might be useful to someone in the future:
def myfunc(str, nth):
new_str = '' #empty string to hold new modified string
for i,l in enumerate(str): # enumerate returns both, index numbers and objects
if i % nth == 0: # if index number % nth == 0 (even number)
new_str += l.upper() # add an upper cased letter to the new_str
else: # if index number nth
new_str += l # add the other letters to new_str as they are
return new_str # returns the string new_str
A simplified answer would be:
def make_nth_letter_capital(word, n):
return word[:n].capitalize() + word[n:].capitalize()
You can use:
def capitalize_nth(text, pos):
before_nth = text[:pos]
n = text[pos].upper()
new_pos = pos+1
after_nth = text[new_pos:]
word = before_nth + n + after_nth
print(word)
capitalize_nth('McDonalds', 6)
The outcome is:
'McDonaLds'
I think this is the simplest among every answer up there...
def capitalize_n(string, n):
return string[:n] + string[n].capitalize() + string[n+1:]
This works perfect

Reverse each word in a string

I am having a small problem in my code. I am trying to reverse the words and the character of a string. For example "the dog ran" would become "ehT god nar"
The code almost works. It just does not add spaces. How would you do that?
def reverseEachWord(str):
reverseWord=""
list=str.split()
for word in list:
word=word[::-1]
reverseWord=reverseWord+word+""
return reverseWord
You are on the right track. The main issue is that "" is an empty string, not a space (and even if you fix this, you probably don't want a space after the final word).
Here is how you can do this more concisely:
>>> s='The dog ran'
>>> ' '.join(w[::-1] for w in s.split())
'ehT god nar'
def reversed_words(sequence):
return ' '.join(word[::-1] for word in sequence.split())
>>> s = "The dog ran"
>>> reversed_words(s)
... 'ehT god nar'
name=input('Enter first and last name:')
for n in name.split():
print(n[::-1],end=' ')
You can also deal with noise in the string using the re module:
>>> import re
>>> s = "The \n\tdog \t\nran"
>>> " ".join(w[::-1] for w in re.split(r"\s+", s))
'ehT god nar'
Or if you don't care:
>>> s = "The dog ran"
>>> re.sub(r"\w+", lambda w: w.group(0)[len(w.group(0))::-1], s)
'Teh god nar'
def reverse_words(sentence):
return " ".join((lambda x : [i[::-1] for i in x])(sentence.split(" ")))
Another way to go about it is by adding a space to your words reverseWord=reverseWord+word+" " and removing the space at the end of your output by using .strip()
def reverse_words(str):
reverseWord = ""
list = str.split()
for word in list:
word = word[::-1]
reverseWord = reverseWord + word + " "
return reverseWord.strip()
check out this post on how it's used
Here is a solution without using join / split :
def reverse(sentence):
answer = ''
temp = ''
for char in sentence:
if char != ' ':
temp += char
continue
rev = ''
for i in range(len(temp)):
rev += temp[len(temp)-i-1]
answer += rev + ' '
temp = ''
return answer + temp
reverse("This is a string to try")

Categories