0
f = open("text.txt","r")
for x in f:
    capitalized_version = x.capitalize()
    print(capitalized_version)

text.txt contains: hello my name is

and it converts it to: Hello my name is

but i want to capitalize all first letters, so Hello My Name Is from the text.txt and put it in a new file text2.txt

This is my first post on stackoverflow so help would be appreciated! :)

l33t
  • 133
  • 6
  • use [`str.title()`](https://docs.python.org/3/library/stdtypes.html#str.title) – norok2 Dec 08 '19 at 15:43
  • Hi and welcome. I'm sure you already know this, but your first interaction with SO should always be an attempt to find an existing answer, not to ask a duplicate question. – Mad Physicist Dec 08 '19 at 15:48
  • Thank you for the feedback, i'll keep that in mind :) – l33t Dec 08 '19 at 15:53

2 Answers2

0

Try x.title() instead of x.capitalize(). See str.title()

OR

make first letter upper case of all words in the file

import re
with open('text.txt', 'r') as file:
   the_string = file.read()
   result = re.sub(r'(((?<=\s)|^|-)[a-z])', lambda x: x.group().upper(), the_string)
   print(result)

DEMO: https://rextester.com/CCJF78043

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

You have the method str.title that can do it:

for x in f:
    capitalized_version = x.title()
    print(capitalized_version)

From the docs:

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.


This solution can be buggish with quotes or other special characters. The documentations suggests using regular expressions, if needed:

>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0).capitalize(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64