String – Alphabet Range in Python

Loop

A string is an array of characters. A character is anything that you can type through your keypad right now. It can be a letter, a number or a space, or even a backspace. Each of these characters can be represented as an ASCII value. ASCII is also known as the American standard code for information interchange. It is a 7-bit encoding format that can be used to identify any character possible in standard computers.

All the alphabet can be represented using ASCII values. There are different ASCII values for lowercase and uppercase characters. The lowercase characters range from ASCII values 197-122, and the uppercase characters range from ASCII values 65-90.

Python is a great language for working with strings. It provides a lot of in-built functionalities to work with strings. On top of that, it also has an in-built method of string slicing, enhancing the capabilities of working with strings. And even if that’s not enough, Python also has a string module as part of the standard Python library, which has numerous more functionalities for string manipulation.

In this article, we’re going to explore strings in Python and, more specifically, the string module of Python and learn to get a range of alphabets as a string and manipulate strings using different functionalities available in Python.

Python String Methods

Python has a lot of in-built functions to manipulate strings. These functions are known as string methods. These methods are simple, powerful, and easy to use. Let’s explore some of the common string methods available in Python and see how we can use them.

How to apply a string method?

A string method can be applied to any string just by adding the string method name after a period after the string.

"<string>".<string-method>()

Applying a string method always returns a new value. So the new value can either be printed or stored in a variable, but there’s no way in Python to change the actual string as stings in Python are immutable.

If you use the dir() method on a string, you can get a list of all the possible string methods in Python.

print(dir(""))
String Methods
String Methods

The methods in the format “__<method>__” are known as magic or dunder methods. They can’t be applied like other string methods, and they have their way. For example, the __add__ method specifies what should happen when you try to use the “+” operator on two different strings. Similarly, all these magic methods specify something.

The string methods, which are not magic methods are everything that you see from the capitalize() method to the zfill() method. These methods may return another string or a boolean value.

capitalize()

The capitalize method changes the first character to uppercase and keeps the rest lowercase.

Capitalize Method Python
Capitalize Method Python

format()

The format() method allows you to put dynamic values in a string. It is the most commonly used string method and has great applications. You put get values and put them into the strings during the runtime. So it’s even possible to take these values as user input.

name = "Rahul"
print("hi, my name is {}.".format(name))
Format Method Example
Format Method Example

To use the format method, we just have to put curly braces wherever we want to enter dynamic values. After the string, use the .format() method and enter the value or variable name you want to put inside the string. So in output, the {} will be replaced by your desired value.

strip()

The strip() method allows you to remove specific characters from the left and right of the string. By default, it removes spaces from the start and the end, but you can pass any string as the argument in the strip() method, and it will remove them from the start and the end if present.

greeting = "    Hello everyone! Welcome to astPython.          "
print("|"+greeting+"|")
greeting = greeting.strip()
print("|"+greeting+"|")
Strip Method Python Example
Strip Method Python Example

In the above block of code, we created a string with some whitespaces at the beginning of the string and some at the end. Then we used the ".strip()" method on it. It removed that whitespace from the start and the end and left the remaining string as it is.

Note: If you just want to remove the trailing character, use the .lstrip() method, and if you only want to remove the leading character, use the .rstrip().

You also have many methods which check what type of character it is and returns True if it matches else it returns a False value. For example, the ".isalpha()" checks whether the character is an alphabet or not. The ".isdigit()" checks whether the character is a number or not.

String Slicing

String slicing is the process of extracting a part of a string out of it. This substring can be a continuous string, or it even can be different parts of the same string.

greeting = "Hello everyone! Welcome to astPython."
print(greeting[16:len(greeting)-1])
Example Of String Slicing In Python

In the above code, we sliced the string “Welcome to askPython” from the greeting string. We just put the starting index and the ending index of the slice we want in a square bracket after the string. The starting index and the ending index must be separated by a colon.

Related: Learn more about string slicing.

Alphabet Range In Python

Alphabets are all the letters in the English language. It can be lowercase or uppercase. The string module in Python provides functionalities to generate an alphabet range in Python. Before we start generating a range of alphabets, let’s see how can we generate an alphabet ourselves.

Generating a single character

Python has an in-built method "chr()" to generate a character using its ASCII value. The chr() method takes an integer as input. It returns the corresponding character of this ASCII value.

print(chr(97))

OUTPUT
a

You can generate any character this way by just its ASCII value.

Now, if we create a loop from 97 to 122 and add each character of each ASCII value into a single string, we’ll get a string of a range of all the lowercase alphabets. Let’s try it out.

Generating a range of alphabets using a for loop and the chr() method

alphabets = ""
for i in range(97,123):
    alphabets += chr(i)
print(alphabets)
Generating A Range Of All The Lowercase Alphabets With Chr Method
Generating A Range Of All The Lowercase Alphabets With Chr Method

First, we created empty string alphabets. Then we created a loop from 97 to 122. Then for each number, we generated its corresponding character, which is a lowercase alphabet, and added it to the alphabet string.

This way, we can generate any range of alphabets through their ASCII value and chr() method.

Using the list comprehension to generate alphabet

You can generate a list of all the alphabet using list comprehension.

Related: Learn list comprehension in depth.

alphabets = [chr(i) for i in range(97, 123)]
print(alphabets)
Using Range Method To Get A List Of All Alphabets
Using Range Method To Get A List Of All Alphabets

In the above code, we created list alphabets using list comprehension for numbers of the range 97 to 122. Now if you want, you cant convert it to a string using the .join() method.

alphabets = ''.join(alphabets)
print(alphabets)

OUTPUT
abcdefghijklmnopqrstuvwxyz

Now you can slice the string if you need only a particular range but not all the alphabet. You can even specify a different range of ASCII values. Let’s see how we can get all the alphabet from “c” to “u”.

start = "c"
end = "u"
alphabets = [chr(i) for i in range(ord(start), ord(end)+1)]
print(alphabets)
Getting A Particular Range Of Alphabets

In the above block of code, we set the starting character as c and the ending character as u. Now we used the list comprehension the same way as before. In the range() function, we specified the starting value as the ASCII value of the character c and the ending. as the ASCII value of the character u. We used the ord() method to get that.

Here you can specify a valid range of any characters. You can even take the starting character and ending character as user input.

Conclusion

Python has great functionalities to work on strings. The string module makes working on strings even easier. It has functions to generate an alphabet range. But it’s always good to stick to the basics and understand how stuff works at a low level. Using a function may get your work done but it won’t give you flexibility in case you want to make changes. So learn as much as you can and remember to keep the basics clear.

References

Official Python documentation.

Stack Overflow answer for the same question.