Python How to capitalize nth letter of a string - python

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

Related

Uppercase the second letter of each word in 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'

Find words in a string of text (where letters aren't consecutive)

I'd like write code to find specific instances of words in a long string of text, where the letters making up the word are not adjacent, but consecutive.
The string I use will be thousands of characters long, but a as a shorter example... If I want to find instances of the word "chair" within the following string, where each letter is no more than 10 characters from the previous.
djecskjwidhl;asdjakimcoperkldrlkadkj
To avoid the problem of finding many instances in a large string, I'd prefer to limit the distance between every two letters to 10. So the word chair in the string abcCabcabcHabcAabdIabcR would count. But the word chair in the string abcCabcabcabcabcabcabcabcabHjdkeAlcndInadhR would not count.
Can I do this with python code? If so I'd appreciate an example that I could work with.
Maybe paste the string of text or use an input file? Have it search for the word or words I want, and then identify if those words are there?
Thanks.
This code below will do what you want:
will_find = "aaaaaaaaaaaaaaaaaaaaaaaabcCabcabcHabcAabdIabcR"
wont_find = "abcCabcabcabcabcabcabcabcabHjdkeAlcndInadhR"
looking_for = "CHAIR"
max_look = 10
def find_word(characters, word):
i = characters.find(word[0])
if i == -1:
print("I couldnt find the first character ...")
return False
for symbol in word:
print(characters[i:i + max_look+1])
if symbol in characters[i:i + max_look+1]:
i += characters[i: i + max_look+1].find(symbol)
print("{} is in the range of {} [{}]".format(symbol, characters[i:i+ max_look], i))
continue
else:
print("Couldnt find {} in {}".format(symbol, characters[i: i + max_look]))
return False
return True
find_word(will_find, looking_for)
print("--------")
find_word(wont_find, looking_for)
An alternative, this may also work for you.
long_string = 'djecskjwidhl;asdjakimcoperkldrlkadkj'
check_word = 'chair'
def substringChecker(longString, substring):
starting_index = []
n , derived_word = 0, substring[0]
for i, char in enumerate(longString[:-11]):
if char == substring[n] and substring[n + 1] in longString[i : i + 11]:
n += 1
derived_word += substring[n]
starting_index.append(i)
if len(derived_word) == len(substring):
return derived_word == substring, starting_index[0]
return False
print(substringChecker(long_string, check_word))
(True, 3)
To check if the word is there:
string = "abccabcabchabcaabdiabcr"
word = "chair"
while string or word:
index = string[:10].find(word[0])
if index > -1:
string = string[index+1:]
word = word[1:]
continue
if not word:
print("found")
else:
break

How do I swap a letter with its immediate neighbor in a string?

I am trying to create a function that takes a string as an argument and returns a list of all of the generated words by swapping a letter with its immediate neighbor.
I first take each letter and create a list of strings and each string contains one letter.
Then I iterate through the new list of letters and try to swap them.
Then I join the letters together to form a string.
Then I append the new string to the list that I return.
Here is my code. Please tell me how to fix it. I don't want it to display the passed word in the list. Thank you.
def mixedString(word):
word = word.lower()
letters = []
newArray = []
for n in word:
letter = f"{n}"
letters.append(letter)
newList = []
for i in range(len(letters)):
newWord = ""
newArray = letters[i:] + letters[:i]
newWord = "".join(newArray)
newList.append(newWord)
return newList
myWord = "Dog"
print(mixedString(myWord))
Hint: there are only n - 1 distinct words where one letter of the original word has been swapped. To see why, note that ab only has ba as result.
If a word has the letters are position i and i+1 swapped the letters before i are unchanged and the letters after i + 1 also are unchanged.
def swap(s, i):
return s[:i] + s[i+1] + s[i] + s[i+2:]
def neighbors(s):
return [swap(s, i) for i in range(len(s)-1)]
You can swap letters like this:
def swap(string, place_1, place_2):
string = list(string)
string[place_1], string[place_2] = string[place_2], string[place_1]
return ''.join(string)
a = '1234'
print(swap(a, 1, 2))
>>> 1324
There are many points of improvement, but I will be addressing the one you ask for
I don't want it to display the passed word in the list.
Just skip the first iteration in the relevant loop, e.g. by replacing this:
for i in range(len(letters)):
with this:
for i in range(1, len(letters)):

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

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

Categories