Simple question about the title() command

Asked

Viewed 155 times

2

if I put for example the name:

Roberto justo da silva

using the title he gets like this:

Roberto Justo Da Silva

How do I make the command title do not change the word 'da' to look like this:

Roberto Justo da Silva

Obviously I used a simple example but I would like it to change if I had the names in a file txt and with several surnames where 'da' appears in different places.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

3 answers

3

Not a command is a method and it can only be applied to data of type string. Documentation. It is quite basic and does not treat exceptions, which in fact decreases its usefulness. So you have to create something manual that sweeps through the whole string and modify the letter box according to the rules you set. That is, you have to create an algorithm of parse. If you don’t care about efficiency you can use this method but treat these words a little differently in another step. It has already been shown how it is done in PHP. There you could help more because there was an attempt, here the question is more conceptual, so the answer is more conceptual.

2

Using the idea of the friend above I made a function to give you an idea to maybe solve your problem.

def newTitle(name):
    name=name.split(' ')
    exceptions=['da','de']
    titledName=''
    for i in name:
        if i in exceptions:
            titledName+=i
        else:
            titledName+=i.title()
        titledName+=' '
    return(titledName[:len(titledName)-1])

1


A good way to do this is by separating your input string with a split by space, then you’ll save it in a array de string. Now just compare the array elements, when the element is equal to da ou de does not apply the title to it i=0 string_nome=input("Digite o nome:") nome_dividido=string_nome.split(' ') while(len(nome_dividido)>i): print(nome_dividido[i]) if(nome_dividido[i] == 'da' or nome_dividido[i] == 'de'): nome_dividido[i]=nome_dividido[i] else: nome_dividido[i]=str.title(str(nome_dividido[i])) i=i+1 print(nome_dividido) The only problem is that you will need to turn this array into a string again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.