简体   繁体   中英

How to get the 1st letter of each word capital in a string of sentence using loops but not methods? in python

my_str = 'peter piper picked a peck of pickled peppers.'

word= ' '
out = ''

for i in range(len(my_str)):
    if my_str[i] ==' ':
    out = out + word.title()
    word =' '
else:
    word = word + my_str[I]
out = out + word.title()
print(out)

I am getting results using methods inside the loop... How can I get the same result using loops but not methods?

You could get the capital of a character without using a built-in method by using this function. It loops through ascii_lowercase and once the element of it is equal to the character you passed, it returns the element in the corresponding index from ascii_lowercase .

from string import ascii_lowercase, ascii_uppercase    

def get_title(letter):
    for index in range(len(ascii_lowercase)):
        if ascii_lowercase[index] == letter:
            return ascii_uppercase[index]

So essentially, if you want to get the capital of each first letter, you could try this.

my_str = 'peter piper picked a peck of pickled peppers.'
my_str += " "

word = ""
sentence = ""
for char in my_str:
    if char == " ":
        sentence += get_title(word[0]) + word[1:len(word)] + " "
        word = ""
    else:
        word += char

print(sentence)

Here, each word is stored when there is a space which is why a space is added to the end of my_str initially. After getting the word, the first element of word (capitalized with get_title ) and the rest is added to sentence .

Here is a very naive method without any string method. In summary keep a flag True on spaces. If the flag is set and you have a lowercase letter, make it uppercase. Then set the flag False.

my_str = 'peter piper picked a peck of pickled peppers.'

out = ''
up = True

low, high = ord('a'), ord('z')
shift = ord('A') - low
for char in my_str:
    o = ord(char)
    if up:
        if low <= o <= high:
            char = chr(o+shift)
        up = False
    if char == ' ':
        up = True
    out += char

out

Output: 'Peter Piper Picked A Peck Of Pickled Peppers.'

NB. This is less efficient than using string methods, in particular due to the repeated string concatenation. Also this only works on ASCII letters.

ord is used to convert it to unicode and then minus that value with 32 to make it capitalize and in final step chr it convert back to character

a = 'this is awesome'
b = ''
for each in range(0,len(a)):
    if each == 0 or a[each-1] == ' ':
        x = ord(a[each])
        y = x - 32
        z = chr(y)
    else:
        z = a[each]
    b += z

Output

This Is Awesome

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM