Python capitalize all words

How To Capitalize All Words in a String in Python

For this task, we’ll be using a handful of Python techniques in order to split, modify, and rebuild our string so that the first letter in each word is capitalized.

Let’s start with a brief overview of each puzzle piece, so we can review the solution more clearly.

  • The .split() String Method: This method will convert a string into a list, taking a single optional parameter as the delimiter to split the string by. If no delimiter is specified, then any white space will be used to split the string.
  • List Comprehension: A truly powerful tool in your Python tool belt, list comprehensions are a way of creating a list from an iterable and an optional conditional expression. Each item from the iterable may be modified within the comprehension, allowing for extremely concise and performant code.
  • The .capitalize() String Method: This method will return the string with its first letter capitalized.
  • The .join() String Method: This method will take a given list and convert it to a string, using the supplied value as a delimiter. If you come from a JavaScript background, you may be used to .join() being an array method — however, in python, it is a string method. The string delimiter is supplied as the base object and the list is passed as an argument to .join() .
Читайте также:  Java генерация случайного кода

The Solution

Now that we’re more familiar with each piece of the solution, let’s get into it.

We first set our string value and then split it into a list:

message = "hello world"parts = message.split(" ")

We separate each word by passing an empty space to .split() . If we were splitting a sequence of comma-separated values the method call would be .split(«,») .

Next, we will use a list comprehension alongside the .capitalize() method to modify the first letter of each string:

capitalized_parts = [p.capitalize() for p in parts]

What’s happening here is we loop through parts , assigning each item to the variable p . Then the resolution of p.capitalize() is passed to our newly…

Источник

Capitalize letters in Python

Learn Algorithms and become a National Programmer

Python has many built-in methods that perform operations on strings. One of the operations is to change the case of letters. We’ll see different ways to change the case of the letters in a string, and go through many examples in each section, and finally go through some of the applications.

Python strings are immutable, which means that once created these strings cannot be modified. As a consequence, most of the functions that operate on strings actually return a modified copy of the string; the original string is unchanged.

Let’s take a look at some of the ways we can manipulate strings to change the case of words.

Different cases

We have covered different cases like:

  • Capitalize the first letter using capitalize()
  • Convert the entire string to upper-case
  • Convert the entire string to lower-case
  • Capitalize first letter of each word

Capitalize the first letter using capitalize()

To capitalize the first letter, use the capitalize() function. This functions converts the first character to uppercase and converts the remaining characters to lowercase. It doesn’t take any parameters and returns the copy of the modified string.

s = "hello openGeNus" t = s.capitalize() print(t) 

Notice that the function capitalize() returned a modified copy of the original string. This means that our original string s was not modified.
The first letter ‘h’ was converted to ‘H’. Further an upper-case letter ‘G’ was converted to its lower-case letter ‘g’ and similarly ‘N’ was converted to ‘n’

Convert the entire string to upper-case

To convert all the letters of the string to uppercase, we can use the upper() function. The function does not take any parameters and returns the copy of modified string with all letters converted to upper-case.

s = "hello openGeNus" t = s.upper() print(t) 

Convert the entire string to lower-case

To convert all the letters of the string to lowercase, we can use the lower() function. This function does not take any parameters and converts all the letters to lowercase.

s = "hello openGeNus" t = s.lower() print(t) 

Capitalize first letter of each word

To capitalize the first letter of each word use the title() function. This function does not take any parameters and converts the first letter of each word to uppercase and rest of the letters to lowercase and returns the modified copy of the string.

s = "hello openGeNus" t = s.title() print(t) 

Notice that while each word was capitalized, the rest of the letters were converted to lowercase.

Applications

Now that we know how to perform basic case-manipulation, lets see how can this be useful for us?
There are many simple applications, we’ll go through some of the basic ones.

Prompts

A prompt is a text message that prompts the user to enter some input. For example, a prompt to enter a number.

A simple prompt could be to allow user to provide a permission by typing the word ‘Yes’. In python «Yes», «yeS» or «YES» are all distinct strings, and we need to be able to accept all variants of those. We can write code to check each of those individually, but the lower() or upper() function provides an easy way.

Let’s go through some sample code

in = input("Type 'Yes' to continue or 'No' to abort: ") if in.lower() == "yes": print("task continued") # . more functions else: print("task aborted") # user did not type Yes 

Here, we checked for input ‘Yes’ and every other input would be considered as a ‘No’. This is sometimes useful, but adding a check for ‘No’ might be required; especially when you want to provide additional messages when user types invalid inputs like a number, instead of ‘Yes’ or ‘No’.

Searching names

Usually, to speed up searching process, names are better stored in the same case. This is done only when the changing the case would not cause any problems. The reason why you’d want to do this could be to make searching faster. Searching for someone named Alice as «ALice», «ALICE» or «alice» could be confusing and lead to unnecessary work.

To overcome this problem, names could be stored in upper-case by using the upper() or in lowercase using the lower() function. This would allow for faster searches because now you don’t have to convert all the names while you perform searches which can be time consuming if there are many names or if the search is occurring multiple times. This is usually done in a students list of names, where case of the names would not matter.

E-mail addresses

E-mail addresses are not case-sensitive. So in an application that requires sign in, you have to be able to handle all types of email address inputs.

Email addresses like «example@example.com», «Example@example.com» or «EXAMPLE@example.com» are all same email addresses, but different python strings. Thus the input needs to be converted to lower-case, which is common format for email addresses.

Here, the lower() function would be useful.

uname = input("Enter your email id: ") temp = uname.lower() if search(temp): # search() defined elsewhere passwd = input("Enter your password: ") else: print("account not found") 

here, we have assumed that there is a function search() that searches for temp and returns a boolean value depending on whether or not the email was found.

Rohit Topi

Intern at OpenGenus | B.Tech Computer Science Student at KLS Gogte Institute Of Technology Belgaum | Contributor to OpenGenus book: «Binary Tree Problems: Must for Interviews and Competitive Coding»

Benjamin QoChuk, PhD

Benjamin QoChuk, PhD

OpenGenus Tech Review Team

Software Engineering

Binary Search in a Linked List

You are given a sorted singly linked list and a key (element to be searched), find the key in the linked list using binary search algorithm. The challenge is to find the middle element as Linked List does not support random access.

Disadvantages of GANs || Am I real or a Trained Model to write?

We have explored the problems with GANs in this article and have divided them into two major parts: General Problems with GANs and Technical Disadvantages of GANs.

Источник

Оцените статью