-3

Is there a way to enter a sentence str and capitalize all the names in it?

test_str = 'bitcoin is not dead and ethereum is cool'

I wish to convert it to

test_str = 'Bitcoin is not dead and Ethereum is cool'

Is this possible? My first thought is to use the re module to locate the name then modify it but then realized the names don't seem to have a specific pattern.

Mike
  • 4,041
  • 6
  • 20
  • 37
  • 2
    If you know which words are proper names, sure. That's the real problem. – khelwood Nov 27 '18 at 14:19
  • You would first need to have a way to determine what is a "name". – Cory Kramer Nov 27 '18 at 14:20
  • 1
    Possible duplicate of [How to capitalize the first letter of each word in a string (Python)?](https://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python) – JackNavaRow Nov 27 '18 at 14:20
  • @JackNavaRow This question only wants to capitalise proper names, not every word. It's not a duplicate of that question. – khelwood Nov 27 '18 at 14:20
  • @khelwood JackNavaRow's linked question could be easily modified to only capitalize known words (names). – Ctrl S Nov 27 '18 at 14:21
  • @CtrlS Yes, easily as long as the OP knows which words are proper names. My reading of the question is that he does not. – khelwood Nov 27 '18 at 14:23
  • 1
    @khelwood if the names are unkown, the problem is unsolvable. If the real question is "How to compare substrings to a list of known strings/names" then that's a different story (and the question should be reworded). – Ctrl S Nov 27 '18 at 14:24
  • @CtrlS I wasn't saying it was a good question. – khelwood Nov 27 '18 at 15:13
  • @khelwood No worries, and I agree that from reading the question it can be assumed that the names are not known by the OP. I was just pointing out that, to the best of my knowledge, the question is not solvable without knowing what words are to be capitalized and that the linked question would have the information required to solve the problem if the names were known. – Ctrl S Nov 27 '18 at 19:35
  • @khelwood thanks for replying to my question!! – Miker Shin Nov 28 '18 at 09:54

2 Answers2

2

If you have a list of words you want to capitalize you can do it as follows:

names = ['bitcoin', 'ethereum']
test_str = 'bitcoin is not dead and ethereum is cool'
output_str = ' '.join([word.capitalize() if word in names else word for word in test_str.split()])

>>> 'Bitcoin is not dead and Ethereum is cool'
berkelem
  • 2,005
  • 3
  • 18
  • 36
0

If there is a list of words you want to capitalize, you can do it using lists.

test_str='bitcoin is not dead and ethereum is cool'
capitalized_words=['bitcoin','ethereum']
for i in range(capitalized_words):
    test_str = test_str.replace(capitalized_words[i],capitalized_words[i].capitalize())
DovaX
  • 958
  • 11
  • 16