Reputation: 13
archive= ['Frederick the Great',
'Ivan the Terrible',
'maurice Of Nassau',
'Napoleon BONAPARTE']
n=[]
n2=[]
n3[]
for line in archive:
n.append(line)
for x in n :
lw = x.lower()
for i in lw.split() :
n2.append(i)
for i in n2 :
if i == 'of' or i == 'the' :
i=i.lower()
n3.append(i)
else:
i=i.capitalize()
n3.append(i)
print(n3)
this code prints the names as strings, how could .join()
be used to do that or using some other method making so that the output would be words in the names are capitalized, the and of are in lowercase and together.
PS:Still new to programming sorry for any mistakes in the formulation of the question.
Upvotes: 1
Views: 141
Reputation: 13362
Expecting there are no quotations or punctuations, you can do as follows
archive = ['Frederick the Great',
'Ivan the Terrible',
'maurice Of Nassau',
'Napoleon BONAPARTE']
reformated = [
' '.join(word.capitalize()
if word not in ('the', 'of')
else word
for word in line.lower().split())
for line in archive
]
['Frederick the Great',
'Ivan the Terrible',
'Maurice of Nassau',
'Napoleon Bonaparte']
Upvotes: 1
Reputation: 8437
Another solution:
archive= [
'Frederick the Great',
'Ivan the Terrible',
'maurice Of Nassau',
'Napoleon BONAPARTE'
]
lines = []
for line in archive:
line = line.lower().split()
for i, word in enumerate(line):
if word in ('of', 'the'):
continue
line[i] = word.capitalize()
lines.append(' '.join(line))
print lines
The advantage of this solution is that it lowers the line in 1 shot, and just continues to the next word when the word if 'of' or 'the', which saves processing cycles.
Upvotes: 0
Reputation: 5389
I write the short function to do capitalize the given string. You can use map
in order to apply to all list of string in the list.
archive= ['Frederick the Great',
'Ivan the Terrible',
'maurice Of Nassau',
'Napoleon BONAPARTE']
def capitalize_phrase(text):
s_capitalize = []
for s in text.split(' '):
if s.lower() in ['the', 'of']:
s_capitalize.append(s.lower())
else:
s_capitalize.append(s.capitalize())
return ' '.join(s_capitalize)
print(list(map(capitalize_phrase, archive)))
Upvotes: 0