The post How to Search for a String in a Text File Through Python appeared first on PythonForBeginners.com.
]]>Text files can hold many different types of data. It’s not uncommon to need to search these files for strings. The Python standard library includes many functions and modules that simplify the process of searching for strings in text files.
Before we can search for a string in a text file, we’ll need to read the file’s contents. The readlines() method reads a file’s data and return a list of the lines it contains. Each element in the list will contain a line from the text file.
In our first example, we’ll create a new text file and search it for a specific string. We’ll use the readlines() method to read the file’s data. Then we’ll assign that data to a variable called lines.
With the list of lines in hand, we can use a for loop to iterate through the text file and search for any lines containing the string “magician.” If one is found, the entire line is printed to the terminal.
Example: Find a string in a text file with readlines()
# create a new text file and write some text
text_file = open("text_file.txt",'w')
text_file.write("The magician appeared without a sound.")
text_file.close()
# safely open the text file we created and search for a string
with open("text_file.txt",'r') as text_file:
lines = text_file.readlines()
for line in lines:
if "magician" in line:
print(line)
Output
The magician appeared without a sound.
Another method we can use to read data from a text file in Python is read(). This method returns a string containing a file’s contents.
Using the read() method, we’ll search the following text file for the word “magician.” If the word we’re looking for is in the text file, the program will let us know by printing “True” to the console.
magic_story.txt
The magician appeared without a sound.
A nervous laugh escaped her lips. She heard the clock ticking
and realized the magician had changed his shape since the last
time she’d seen him. Julia felt her heart leap into her throat.
Example: Using the read() method to search a text file
story_file = open("magic_story.txt",'r')
story_text = story_file.read()
story_file.close()
if "magician" in story_text:
print("True")
Output
True
Next, using the story from the previous example, we’ll demonstrate how to count the number of times a word appears in a text file. Sometimes a text file contains many instances of a word or phrase. With Python, it’s possible to count how many times a string occurred in a text document.
In the following example, a Python with statement is used to open the text file and read its contents. Opening a file this way ensures that it is handled safely, and properly closed. With the file opened, the data is converted to a list of strings via the readlines() method.
Lastly, an f-string is used to print the results.
Example: Counting lines of text that contain a specific string
with open("magic_story.txt",'r') as text_file:
lines = text_file.readlines()
count = 0
for line in lines:
if "magician" in line:
count += 1
print(f"Found 'magician' {count} times.")
Output
Found 'magician' 2 times.
So far we’ve seen how to search a text file for a string. But what if we need more information? Suppose we want to record the lines of text that contain a string. How do we do this with Python?
Probably the easiest way to extract the lines from a file is with a list. For the next example, we’ll search a document for a string and add any lines that contain the string we’re looking for to a list using the append() method.
The append() method is used to add an element to a list. Once an element is added to a list, it can be accessed using brackets. By placing the index of the element inside brackets following the list variable, we can get a reference to that element.
We’ll also need to use the strip() method to remove the newline character from the end of each line. For this exercise, we’ll use the following text, an excerpt from T.S. Eliot’s The Hollow Men.
hollow_men.txt
Between the desire
And the spasm
Between the potency
And the existence
Between the essence
And the descent
Falls the Shadow
Example: Using a list to store lines of text
file = open("hollow_men.txt",'r')
lines = file.readlines()
file.close()
lines_we_want = []
for i in range(len(lines)):
if "Between" in lines[i]:
lines_we_want.append(lines[i].strip("\n"))
print(lines_we_want)
Output
['Between the desire', 'Between the potency', 'Between the essence']
Suggested Reading: If you are into machine learning, you can read this article on regression in machine learning. You might also like this article on k-means clustering with numerical example.
The find() method returns the position of the first instance of a string. If the string isn’t found, this method returns a value of -1. We can use this method to check whether or not a file contains a string.
Example: Using the find() method
text = "Hello World"
print(text.find("Hello"))
print(text.find("World"))
print(text.find("Goodbye"))
Output
0
6
-1
Firstly, we can create a new text file with some example text. Secondly, we’ll open the file using a with statement. After reading the file’s contents, we’ll store the data as a new variable. Finally, using the find() method, we’ll attempt to locate the first instance of the word “magician” and print the results.
Example: Searching a text file for a string with the find() method
# create a new texts file and write some text
text_file = open("new_file.txt",'w')
text_file.write("The magician appeared without a sound.")
text_file.close()
# safely open the text file we created and search for a string
with open("new_file.txt",'r') as text_file:
text_data = text_file.read()
print(text_data.find("magician"))
Output
4
A CSV file stores data as plain text. These files usually contain strings or numbers separated by a comma. That’s why we call them comma-separated value files. These CSV files make it easier for programs to exchange information.
Python comes with a module for reading CSV files. The csv module includes special methods for extracting data from these file types. One such method is reader().
Let’s assume our employee has handed us a file containing a list of user data for a website. Our job is to search this data for particular users. We’ll begin by searching for a user with the handle “the_magician.”
account_info.csv
Username,Email,Joined Date
cranky_jane,[email protected],01-21-2021
the_magician,[email protected],10-10-2020
sergeant_pepper,[email protected],05-15-2020
Before we can find the user’s handle, we’ll need to read the file data. By combining the reader() method with a for loop, it’s possible iterate over the rows of CSV data contained in the text file. If we come across a row containing the username we’re after, we’ll print the row’s data.
Example: Searching a CSV file for a string
import csv
# the string we want to find in the data
username = "the_magician"
with open("account_info.csv",'r') as data_file:
# create a reader object from the file data
reader = csv.reader(data_file)
# search each row of the data for the username
for row in reader:
if username in row:
print(row)
Output
['the_magician', '[email protected]', '10-10-2020']
What if we wanted to search the CSV file for more than one username? We can do this by creating a list of the usernames we want to search for. Comparing each row to the list of usernames makes it possible to locate the account data we’re trying to find.
Example: Search a CSV file for a list of strings
import csv
# the strings we want to find in the data
usernames = ["the_magician","cranky_jane"]
with open("account_info.csv",'r') as data_file:
# create a reader object from the file data
reader = csv.reader(data_file)
# search each row of the data for the username
for row in reader:
for username in usernames:
if username in row:
print(row)
Output
['cranky_jane', '[email protected]', '01-21-2021']
['the_magician', '[email protected]', '10-10-2020']
Completing a job is a lot easier when you have the proper tools. That’s why it’s important to learn about the many features of Python. In order to search for strings in text files, we needed to learn about methods like readlines() and find(). These are versatile methods that are great for solving many different problems.
If you’d like to learn more about Python development, follow these links to other excellent tutorials from Python for Beginners.
The post How to Search for a String in a Text File Through Python appeared first on PythonForBeginners.com.
]]>The post How to Use Python Split Function appeared first on PythonForBeginners.com.
]]>Using split() is a simple and efficient method for breaking down large strings into more manageable parts.
This can be a useful method if we’re tasked with working on text files, as we’ll see later on.
The split() method separates a string into individual words using a delimiter, also referred to as the separator. Python uses whitespace as the default separator, but you are free to provide an alternative.
The separator can be anything, but it’s generally a character used to separate the words in a string. For example, a comma is often used to break up a list.
# the following string uses a comma as the separator.
groceries = “Bread,Milk,Eggs,Bananas,Coffee”
The split() function will return a list of strings. By default there is no limit to how long the returned list can be. But you can change this with the maxsplit setting.
Syntax:
my_string.split(separator,maxsplit)
separator: This is the delimiter Python will use to split the string. Whitespace is used as the separator if one is not provided.
maxsplit: This setting is used to determine how many times the string should be split. This list has no limit by default.
There are plenty of good reasons to use the split() function. Whether you’re working with a comma separated value (CSV) file, or simply trying to break down a large string into smaller pieces, split() offers an efficient means of splitting strings in Python.
The split() function will break a string into list of words. These are given back to us in the form of a Python string array.
Here’s a step-by-step guide to using split():
gandalf = "You shall not pass."
gandalf.split() # The string will be split based on whitespace.
Here’s what it looks like when we split the string.
['You', 'shall', 'not', 'pass.']
Use the split() function with python string concatenation to quickly join and split strings. The split() function is also great for quickly parsing comma separated value (CSV) files.
When we use the split() function to split a string, Python returns a new string array. This array holds the split string.
For example. If we have a string that looks like this:
frosty_string = "Some say the world will end in fire."
We can see that the words of the string are separated by whitespace. Running split() with this string would return a new array containing the words of the opening line of a famous poem by Robert Frost.
# this line is from Fire and Ice by Robert Frost
frosty_string = "Some say the world will end in fire."
words = frosty_string.split()
print(words)
Output
['Some', 'say', 'the', 'world', 'will', 'end', 'in', 'fire.']
It’s also possible to use split() to break a list into a predefined number of parts. As we saw in its definition, the split() function takes an optional second argument. By setting maxpslit, we can tell Python to break the list into two pieces.
fruit = "Apples Oranges"
# setting maxsplit to 1 will return a list with 2 parts
two_max = fruit.split(' ', 1)
print(two_max)
Output
['Apples', 'Oranges']
We’ve seen a basic use of the split() function. By default, split() uses whitespace to split strings. While whitespace works for some data, other characters often make more sense. It’s common to use a comma to separate values in a string.
Using commas, we can easily split a large amount of string data quickly. In the following example, a string containing all the instruments in a generic rock band is split into a new list.
# use a comma as the separator
band = "Guitar,Piano,Drums,Trumpet,Bass Guitar,Vocals"
instruments = band.split(',')
print(instruments)
Output
['Guitar', 'Piano', 'Drums', 'Trumpet', 'Bass Guitar', 'Vocals']
Using a comma as the separator makes it easy to convert a string into a list. Converting strings into lists, and vice versa, can be a convenient method of storing and reading data.
I’ve created a text file on my computer called chess.txt. This file is located in the same folder as my Python file.
This text file contains a single line listing the pieces used in a game of chess. Notice that a comma is used to separate the names of the pieces.
King,Queen,Rook,Knight,Bishop,Pawn
By utilizing split(), we can easily separate the game pieces. We’ll use Python’s open() method to read the file and extract the line of text before splitting the string.
file = open("chess.txt")
pieces = file.read().split(',')
print(pieces)
Output
['King', 'Queen', 'Rook', 'Knight', 'Bishop', 'Pawn\n']
Looking back at the last example, you might notice something odd about our list. We’ve picked up some stray characters somewhere. Where did that \n come from?
This is the new line character. It tells Python that we’ve come to the end of the line in a text file.
We can make use of Python’s strip() method to remove the new line character from the end of our list. Using this method will ensure that we don’t pick up any pesky hidden characters from the file, such as the \n character.
file = open("chess.txt")
pieces = file.read().strip().split(',')
print(pieces)
file.close()
Output
['King', 'Queen', 'Rook', 'Knight', 'Bishop', 'Pawn']
The above example was relatively basic. After all, we only had one line of text to deal with. But what if we have rows of data separated by commas? Let’s take a look at what reading a simple database might look like.
We’ll write a program for a teacher who needs to calculate the average grades for each student in his/her class.
Our client needs to keep track of his/her student’s homework. Specifically, he/she would like a way to read the data stored in a text file. The file, called grades.txt, contains the grades of the teacher’s students.
Our teachers_pet.py program will read the information from a file and build a string containing the grade data.
Once we have the string of grades, we can use the split() function to split the grades and store them in a list. After that, we’ll need to convert the strings to numbers using the float() method.
While this is admittedly a convoluted process, the example demonstrates the various ways one can work with numbers and strings in Python.
grades.txt
Noah, 81, 94, 100, 65
Elijah, 80, 84, 72, 79
Lucas, 95, 80, 89, 89
Emma, 95, 80, 80, 77
Ava, 90, 84, 85, 80
Amelia 100, 100, 95, 0
# teachers_pet.py
file = open("grades.txt", 'r')
grade_data = []
while(True):
line = file.readline()
if not line:
break
grade_data.append(line.split(','))
print(grade_data)
file.close()
# this function will loop through the student's grades
def calculate_averages(grades_data):
for grades in grade_data:
total = 0
# the student's name occupies the first spot
for i in range(1,len(grades)):
total += float(grades[i].strip()))
avg = total/float(len(grades)-1)
print("{} has an average of {}.".format(grades[0],avg))
calculate_averages(grade_data)
Output
Noah has an average of 85.0
Elijah has an average of 78.75
Lucas has an average of 88.25
Emma has an average of 83.0
Ava has an average of 84.75
Amelia has an average of 73.75
Our program has two parts. In the first part, we read the data from the file with the open() method. Line by line, the grades of each student are added to a list called grades_data.
We do this by taking advantage of float() to convert the string to a number. We’ll also use strip() to remove any unnecessary characters, such as the \n character.
Keep in mind that the first element in the list of grades is the student’s name.
We also need a function to calculate and print the grade averages. We do this in calculage_averages(). This handy function will look through the grade data and find each student’s grade point average.
Python comes with many built-in functions that can improve your code. The split() function is one such tool that can be used to break up difficult string problems.
Using a separator to divide the string allows you to convert string data into a list of strings, which is easier to manage. The split() function is also a quick way break up text data read from a file.
Learn more about Python and how to improve your programming skills by visiting the following tutorials.
The post How to Use Python Split Function appeared first on PythonForBeginners.com.
]]>The post Convert Tuple to String in Python appeared first on PythonForBeginners.com.
]]>Suppose that we have the following tuple of characters.
myTuple = ("P", "y", "t", "h", "o", "n")
Now, we have to convert this tuple to the string “Python”.
To convert the tuple to string, we will first create an empty string named output_string. After that, We will traverse the tuple using a for loop. While traversal, we will add each character in the tuple to the output_string using the string concatenation operation. After execution of the for loop, we will get the desired string in the variable output_string. You can observe this in the following example.
myTuple = ("P", "y", "t", "h", "o", "n")
output_string = ""
for character in myTuple:
output_string += character
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
Output:
The input tuple is: ('P', 'y', 't', 'h', 'o', 'n')
The output string is: Python
Instead of using the for loop, we can use the join() method to convert the tuple of characters into a string. The join() method, when invoked on a string, takes an iterable object containing strings as an input argument. After execution, it returns the modified string containing the new character along with the characters in the original string.
To convert a tuple of characters to a string, we will first create an empty string named output_string. After that, we will invoke the join() method on the output_string with the tuple as input argument. After execution, the join() method will return the desired string as shown below.
myTuple = ("P", "y", "t", "h", "o", "n")
output_string = ""
output_string = output_string.join(myTuple)
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
Output:
The input tuple is: ('P', 'y', 't', 'h', 'o', 'n')
The output string is: Python
If you try to convert a tuple of numbers to a string using any of the methods discussed above, the program will raise TypeError exception. You can observe this in the following example.
myTuple = (1, 2, 3, 4, 5, 6)
output_string = ""
for character in myTuple:
output_string += character
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
output_string += character
TypeError: can only concatenate str (not "int") to str
Similarly, when we use the second approach, the program runs into TypeError exception as shown below.
myTuple = (1, 2, 3, 4, 5, 6)
output_string = ""
output_string = output_string.join(myTuple)
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
output_string = output_string.join(myTuple)
TypeError: sequence item 0: expected str instance, int found
To avoid the error, we just have to convert each element of the tuple into a string before adding it to the output_string. In the first approach, we will first convert each element of the tuple into a string using the str() function. After that, we will perform the concatenation operation. In this way, we can convert a tuple of numbers to a string.
myTuple = (1, 2, 3, 4, 5, 6)
output_string = ""
for element in myTuple:
character = str(element)
output_string += character
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
Output:
The input tuple is: (1, 2, 3, 4, 5, 6)
The output string is: 123456
For the approach using the join() method, we will first convert the tuple of numbers into a tuple of strings. For this, we will use the map() function and the str() function.
The map() function takes a function as its first argument and an iterable object as the second input argument. After execution, it returns a map object in which the function is applied to each element of the iterable object. We will pass the str() function and the tuple of numbers to the map() function as input arguments. After that, we will convert the map object using the tuple() constructor. Hence, we will get a tuple of strings as shown below.
myTuple = (1, 2, 3, 4, 5, 6)
newTuple = tuple(map(str, myTuple))
print("The input tuple is:", myTuple)
print("The output tuple is:", newTuple)
Output:
The input tuple is: (1, 2, 3, 4, 5, 6)
The output tuple is: ('1', '2', '3', '4', '5', '6')
After getting the tuple of strings from the tuple of numbers, we can directly obtain the string as follows.
myTuple = (1, 2, 3, 4, 5, 6)
newTuple = tuple(map(str, myTuple))
output_string = ''.join(newTuple)
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
Output:
The input tuple is: (1, 2, 3, 4, 5, 6)
The output string is: 123456
In this article, we have discussed how to convert a tuple to a string in python. To know more about strings in python, you can read this article on string formatting in python. You might also like this article on list comprehension in python.
The post Convert Tuple to String in Python appeared first on PythonForBeginners.com.
]]>The post Check if a Python String Contains a Number appeared first on PythonForBeginners.com.
]]>In ASCII encoding, numbers are used to represent characters. Each character is assigned a specific number between 0 to 127 to it. We can find the ASCII value of any number in python using the ord() function.
The ord() function takes a character as its input argument and returns its ASCII value. You can observe this in the following python code.
zero = "0"
nine = "9"
print("The ASCII value of the character \"0\" is:", ord(zero))
print("The ASCII value of the character \"9\" is:", ord(nine))
Output:
The ASCII value of the character "0" is: 48
The ASCII value of the character "9" is: 57
As you can see in the above python program, the ASCII value for the character “0” is 48. Also, the ASCII value for the character “9” is 57. Therefore, any numeric character will have its ASCII value between 48 and 57.
We can use the ASCII values of the numeric characters to check if a string contains a number in python. For this, we will consider the string as a sequence of characters.
After that, we will follow the steps mentioned below.
flag variable. Initially, we will initialize the flag variable to the boolean value False. True to the flag variable, showing that the string contains numerical characters. Here, we have already found that the string contains a number. Therefore, we will exit from the for loop using the break statement.flag variable will contain the value False.After execution of the for loop, we will check if the flag variable contains the value True. If yes, we will print that the string contains a number. Otherwise, we will print that the string doesn’t contain any number. You can observe this in the following code.
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
ascii_val = ord(character)
if 48 <= ascii_val <= 57:
flag = True
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
If you run the code given in the above example with an empty string as its input, the program works as desired. Thus, it is important to initialize the flag variable to False before execution of the for loop. Otherwise, the program will not work as desired.
Python provides us with different string methods with which we can check if a string contains a number or not. The isnumeric() method, when invoked on a string, returns True if the string consists of only numeric characters. If the string contains non-numeric characters, it returns False.
We can check if a string contains only numeric characters or not using the isnumeric() method as shown in the following example.
myStr1 = "123"
isNumber = myStr1.isnumeric()
print("{} is a number? {}".format(myStr1, isNumber))
myStr2 = "PFB"
isNumber = myStr2.isnumeric()
print("{} is a number? {}".format(myStr2, isNumber))
Output:
123 is a number? True
PFB is a number? False
If we are given a string containing alphanumeric characters, you can also check if the string contains numbers or not using the isnumeric() method. For this, we will iterate through the characters of the original string object using a for loop.
isnumeric() method on each character. If the character represents a digit, the isnumeric() method will return True. Hence we can say that the string contains a number.isnumeric() method to the flag variable. flag variable has the value True, it shows that the string contains numeric characters. Once we find that the string contains a number, we will exit from the for loop using the break statement.flag variable will contain the value False.If the flag variable contains the value False after the execution of the for loop, we will say the string contains numbers. Otherwise, we will say that the string does not contain numbers. You can observe this in the following code.
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
flag = character.isnumeric()
if flag:
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
Instead of the isnumeric() used in the previous section, we can use the isdigit() method to check if a string is a number or not. The isdigit() method, when invoked on a string, returns True if all the characters in the string are decimal digits. Otherwise, it returns False. You can observe this in the following example.
myStr1 = "1"
isDigit = myStr1.isdigit()
print("{} is a digit? {}".format(myStr1, isDigit))
myStr2 = "A"
isDigit = myStr2.isnumeric()
print("{} is a digit? {}".format(myStr2, isDigit))
Output:
1 is a digit? True
A is a digit? False
We can also check if a string contains a number or not using the isdigit() method. For this, we will iterate through the characters of the original string object using a for loop.
isdigit() method on each character. If the character represents a digit, the isdigit() method will return True. Hence we can say that the string contains a number.isdigit() method to the flag variable. If the flag variable has the value True, it shows that the string contains numeric characters. flag variable will contain the value False.If the flag variable contains the value False after the execution of the for loop, we will say the string contains numbers. Otherwise, we will say that the string does not contain numbers.
You can observe this in the following code.
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
flag = character.isdigit()
if flag:
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
In the previous sections, we have used various methods to check if a python string contains a number or not. For this, we have traversed the input string using a for loop in each of the examples. However, we can also check if the string contains a number without explicitly iterating the string. For this, we will use the map() function.
The map() function takes a function as its first input argument, say func, and an iterable object say iter as its second input argument. While execution, it executes the function func given in the first input argument with elements of iter as the input argument of func. After execution, it returns a map object that contains the values returned by func when it is executed with the elements of iter as the input arguments.
You can convert the map object into a list using the list() constructor.
For example, look at the following source code.
from math import sqrt
numbers = [1, 4, 9, 16, 25]
print("The numbers are:", numbers)
square_roots = list(map(sqrt, numbers))
print("The square roots are:", square_roots)
Output:
The numbers are: [1, 4, 9, 16, 25]
The square roots are: [1.0, 2.0, 3.0, 4.0, 5.0]
In the above code, we have passed the sqrt() function as the first input argument and a list containing positive numbers as the second argument of the map() function. After execution, we have obtained a list containing the square root of the elements of the input list.
To check if a python string contains a number or not using the map() function, we will create a function myFunc. The function myFunc should take a character as its input argument. After execution, it should return True if the character is a digit. Otherwise, it should return False.
Inside myFunc, we can use the isdigit() method to check if the input character is a digit or not.
We will pass the myFunc() function as the first argument and the input string as the second input argument to the map() method. After execution, the map() function will return a map object.
When we convert the map object into a list, we will get a list of boolean values True and False. The total number of values in the list will be equal to the number of characters in the input string. Also, each boolean value corresponds to a character at the same position in the string. In other words, the first element of the list corresponds to the first character in the input string, the second element of the list corresponds to the second character in the input string, and so on.
If there is any numeric character in the string, the corresponding element in the output list will be True. Therefore, if the list obtained from the map object contains the value True in at least one of its elements, we will conclude that the input string contains numbers.
To find if the output list contains the value True as its element, we will use the any() function.
The any() function takes the list as its input argument and returns True if at least one of the values is True. Otherwise, it returns False.
Thus, if the any() function returns True after execution, we will say that the input string contains a number. Otherwise, we will conclude that the input string does not contain numeric characters.
You can observe this in the following code.
def myFunc(character):
return character.isdigit()
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(myFunc, myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
This method also works well with a larger string as we don’t need to traverse the input string character by character.
Instead of defining myFunc, you can also pass a lambda function to the map() function. This will make your code more concise.
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(lambda character: character.isdigit(), myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
Instead of the isdigit() method, you can also use the isnumeric() method along with the map() function and any() function to check if a python string contains a number as shown in the following example.
def myFunc(character):
return character.isnumeric()
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(myFunc, myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
All the approaches discussed in the previous sections use standard string methods and string values. However, python also provides us with the regular expressions module ‘re’ to process textual data and strings.
Let us now discuss how we can check if a python string contains a number using the regular expressions.
Regular expressions are used to manipulate text data in python. We can also use regular expressions to check if a python string contains a number or not. For this, we can use the match() method and the search() method. Let us discuss both these approaches one by one.
The match() method is used to find the position of the first occurrence of a specific pattern in a string. It takes a regular expression pattern as its first argument and the input string as its second argument. If there exists a sequence of characters of the string that matches the regular expression pattern, it returns a match object. Otherwise, it returns None.
To check if a string contains a number using the match() method, we will follow the following steps.
“\d+”.match() method.match() method returns None, we will say that the string doesn’t contain any number. Otherwise, we will say that the string contains numbers.You can observe this in the following example.
import re
myStr = "23 but it feels like I am 15."
match_object = re.match(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
23 but it feels like I am 15.
String contains numbers?: True
The match() method only works if the number is present at the beginning of the string. In other cases, it fails to check if the given string contains a number or not. You can observe this in the following example.
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.match(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: False
In the above example, you can see that the string contains numbers. However, the program concludes that there aren’t any numbers in the string. To avoid errors in checking for numbers in the string, we can use the search() method instead of the match() method.
The search() method is used to find the positions of a specific pattern in a string. It takes a regular expression pattern as its first argument and the input string as its second argument. If there exists a sequence of characters of the string that matches the regular expression pattern, it returns a match object containing the position of the first occurrence of the pattern. Otherwise, it returns None.
To check if a string contains a number using the search() method, we will follow all the steps that we used with the match() method. The only difference is that we will use the search() method instead of the match() method. You can observe this in the following example.
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.search(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
The search() method searches in the entire string. After execution, it returns a match object having the first occurrence of the input pattern. Hence, even if there is only one digit in the string, the search() method will find that. However, this is not true for the match() method.
The findall() method is semantically similar to the search() method. The difference is that the findall() method returns all the occurrences of the pattern instead of the first occurrence of the pattern. When a pattern isn’t present in the input string, the findall() method returns None.
You can check if a python string contains a number or not using the findall() method as shown below.
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.findall(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
In this article, we have discussed different ways to check if a python string contains a number or not. Out of all these approaches, the approach using regular expressions is most efficient. If we talk about writing more pythonic code, you can use the map() function with the any() function to check if a string contains a number or not. Regular expressions are a better option compared to the string methods. Hence, for the best execution times, you can use the re.search() method to check if a string contains a number or not.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
The post Check if a Python String Contains a Number appeared first on PythonForBeginners.com.
]]>The post Remove All Occurrences of a Character in a List or String in Python appeared first on PythonForBeginners.com.
]]>Given a list, we can remove an element from the list using the pop() method. The pop() method, when invoked on a list removes the last element from the list. After execution, it returns the deleted element. You can observe this in the following example.
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
x = myList.pop()
print("The popped element is:", x)
print("The modified list is:", myList)
Output:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The popped element is: 7
The modified list is: [1, 2, 3, 4, 5, 6]
In the above example, you can see that the last element of the list has been removed from the list after the execution of the pop() method.
However, If the input list is empty, the program will run into IndexError. It means that you are trying to pop an element from an empty list. For instance, look at the example below.
myList = []
print("The original list is:", myList)
x = myList.pop()
print("The popped element is:", x)
print("The modified list is:", myList)
Output:
The original list is: []
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
x = myList.pop()
IndexError: pop from empty list
You can observe that the program has run into an IndexError exception with the message “IndexError: pop from empty list“.
You can also remove the element from a specific index in the list using the pop() method. For this, you will need to provide the index of the element.
The pop() method, when invoked on a list, takes the index of the element that needs to be removed as its input argument. After execution, it removes the element from the given index. The pop() method also returns the removed element. You can observe this in the following example.
myList = [1, 2, 3, 4, 5, 6, 7, 8]
print("The original list is:", myList)
x = myList.pop(3)
print("The popped element is:", x)
print("The modified list is:", myList)
Output:
The original list is: [1, 2, 3, 4, 5, 6, 7, 8]
The popped element is: 4
The modified list is: [1, 2, 3, 5, 6, 7, 8]
Here, We have popped out the element at index 3 of the list using the pop() method.
If you don’t know the index of the element that has to be removed, you can use the remove() method. The remove() method, when invoked on a list, takes an element as its input argument. After execution, it removes the first occurrence of the input element from the list. The remove() method doesn’t return any value. In other words, it returns None.
You can observe this in the following example.
myList = [1, 2, 3, 4,3, 5,3, 6, 7, 8]
print("The original list is:", myList)
myList.remove(3)
print("The modified list is:", myList)
Output:
The original list is: [1, 2, 3, 4, 3, 5, 3, 6, 7, 8]
The modified list is: [1, 2, 4, 3, 5, 3, 6, 7, 8]
In the above example, you can see that the 1st occurrence of element 3 is removed from the list after the execution of the remove() method.
If the value given in the input argument to the remove() method doesn’t exist in the list, the program will run into a ValueError exception as shown below.
myList = []
print("The original list is:", myList)
myList.remove(3)
print("The modified list is:", myList)
Output:
The original list is: []
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myList.remove(3)
ValueError: list.remove(x): x not in list
In the above example, the list is empty. Hence, the number 3 isn’t an element of the list. Therefore, when we invoke the remove() method, the program runs into the ValueError exception with the message “ValueError: list.remove(x): x not in list“.
Till now, we have discussed how to remove an element from a list. Let us now discuss how we can remove all occurrences of a character in a list of characters in python.
Given a list of characters, we can remove all the occurrences of a value using a for loop and the append() method. For this, we will use the following steps.
outputList. For this, you can either use square brackets or the list() constructor.outputList, we will traverse through the input list of characters using a for loop.outputList using the append() method. After execution of the for loop, we will get the output list of characters in outputList. In the outputList, all the characters except those that we need to remove from the original list will be present. You can observe this in the following python program.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
outputList = []
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
for character in myList:
if character == charToDelete:
continue
outputList.append(character)
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Instead of using the for loop, we can use list comprehension and the membership operator ‘in’ to remove all the occurrences of a given character.
The in operator is a binary operator that takes an element as its first operand and a container object like a list as its second operand. After execution, it returns True if the element is present in the container object. Otherwise, it returns False. You can observe this in the following example.
myList = [1, 2, 3, 4,3, 5,3, 6, 7, 8]
print("The list is:", myList)
print(3 in myList)
print(1117 in myList)
Output:
The list is: [1, 2, 3, 4, 3, 5, 3, 6, 7, 8]
True
False
Using list comprehension and the ‘in’ operator, we can create a new list having all the characters except those that we need to remove from the original list as shown in the following example.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList = [character for character in myList if character != charToDelete]
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Instead of creating a new list, we can also remove all the instances of a character from the original list. For this, we will use the remove() method and the membership operator ‘in’.
in’ operator. If yes, we will remove the character from the list using the remove method. In this way, we will get the output list by modifying the original list as shown below.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
while charToDelete in myList:
myList.remove(charToDelete)
print("The modified list is:", myList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
We can also use the filter() function to remove all occurrences of a character from a list of characters.
The filter() function takes another function say myFun as its first input argument and a container object like a list as its second argument. Here, myFun should take an element of the container object as its input argument. After execution, it should return either True or False.
If the output of myFun is True for any element of the container object given in input, the element is included in the output. Otherwise, the elements aren’t included in the output.
To remove all the occurrences of a given item in a list using the filter() method, we will follow the following steps.
myFun that takes a character as an input argument. It returns False if the input character is equal to the character that we need to remove. Otherwise, it should return True. myFun, we will pass myFun as the first argument and the list of characters as the second input argument to the filter() function. filter() function will return an iterable object containing the characters that aren’t removed from the list.list() constructor. In this way, we will get the list after removing all the occurrences of the specified character.You can observe the entire process in the following example.
def myFun(character):
charToDelete = 'c'
return charToDelete != character
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList=list(filter(myFun,myList))
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Instead of defining the function myFun, we can create a lambda function and pass it to the filter function to remove all the instances of character from the list. You can do it as follows.
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList = list(filter(lambda character: character != charToDelete, myList))
print("The modified list is:", outputList)
Output:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
Till now, we have discussed different methods to remove all the occurrences of a character in a list. Now we will discuss how we can remove occurrences of a specific character from a python string.
Given an input string, we can remove one or all occurrences of a character from a string using different string methods as well as a regular expression method. Let us discuss each of them one by one.
To remove all the occurrences of the particular character from a string using the for loop, we will follow the following steps.
outputString to store the output string.outputString. After iterating till the last character of the string using the for loop using the above steps, we will get the output string in the new string named outputString. You can observe that in the following code example.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = ""
for character in myStr:
if character == charToDelete:
continue
outputString += character
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
Instead of using the for loop, we can remove the occurrences of a specific value from a given string using the list comprehension and the join() method.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = [character for character in myStr if character != charToDelete]
print("The list of characters is:")
print(myList)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list of characters is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
join() method to create the output list. The join() method when invoked on a special character, takes an iterable object containing characters or strings as its input argument. After execution, it returns a string. The output string contains the characters of the input iterable object separated by the special character on which the join method is invoked. “” as the special character. We will invoke the join() method on the empty character with the list obtained from the previous step as its input argument. After execution of the join() method, we will get the desired output string. You can observe this in the following example.myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = [character for character in myStr if character != charToDelete]
print("The list of characters is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list of characters is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
We can also use the split() method to remove all the occurrences of a character from a given string. The split() method, when invoked on a string, takes a separator as its input argument. After execution, it returns a list of substrings that are separated by the separator.
To remove all the occurrences of a given character from a given string, we will use the following steps.
split() method on the original string. W will pass the character that has to be removed as the input argument to the split() method. We will store the output of the split() method in myList.myList, we will invoke the join() method on an empty string with myList as the input argument to the join() method.join() method, we will get the desired output. So, we will store it in a variable outputString.You can observe the entire process in the following example.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = myStr.split(charToDelete)
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The character to delete: c
The list is:
['py', 't', 'honf', 'orbeg', 'inn', 'ers']
The modified string is: pythonforbeginners
We can also use the filter() function with the join() method and lambda function to remove the occurrences of a character from a string in Python.
The filter() function takes another function say myFun as its first input argument and an iterable object like a string as its second input argument. Here, myFun should take the character of the string object as its input argument. After execution, it should return either True or False.
If the output of myFun is True for any character of the string object given in input, the character is included in the output. Otherwise, the characters aren’t included in the output.
To remove all the occurrences of a given character in a string, we will follow the following steps.
myFun that takes a character as an input argument. It returns False if the input character is equal to the character that has to be removed. Otherwise, it should return True. myFun, we will pass myFun as the first argument and the string as the second input argument to the filter() function. filter() function will return an iterable object containing the characters that aren’t removed from the string.list() constructor.join() method on an empty string with the list of characters as its input argument. join() method, we will get the desired string. You can observe the entire process in the following code.
def myFun(character):
charToDelete = 'c'
return charToDelete != character
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = list(filter(myFun, myStr))
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
Instead of defining the function myFun, we can create an equivalent lambda function and pass it to the filter function to remove all the instances of the character from the string. You can do it as follows.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = list(filter(lambda character: character != charToDelete, myStr))
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
The replace() method, when invoked on a string, takes the character that needs to be replaced as its first argument. In the second argument, it takes the character that will be replaced in place of the original character given in the first argument.
After execution, the replace() method returns a copy of the string that is given as input. In the output string, all the characters are replaced with the new character.
To remove all the occurrences of a given character from a string, we will invoke the replace() method on the string. We will pass the character that needs to be removed as the first input argument. In the second input argument, we will pass an empty string.
After execution, all the occurrences of character will be replaced by an empty string. Hence, we can say that the character has been removed from the string.
You can observe the entire process in the following example.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = myStr.replace(charToDelete, "")
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
We can also use the translate() method to remove characters from a string. The translate() method, when invoked on a string, takes a translation table as an input argument. After execution, it returns a modified string according to the translation table.
The translation table can be created using the maketrans() method. The maketrans() method, when invoked on a string, takes the character that needs to be replaced as its first argument and the new character as its second argument. After execution, it returns a translation table.
We will use the following steps to remove the given character from the string.
maketrans() method on the input string. We will pass the character that needs to be removed as the first input argument and a space character as the second input argument to the maketrans() method. Here, we cannot pass an empty character to the maketrans() method so that it can map the character to empty string. This is due to the reason that the length of both the strings arguments should be the same. Otherwise, the maketrans() method will run into error.maketrans() method will return a translation table that maps the character we need to remove to a space character.translate() method on the input string with the translation table as its input argument. translate() method will return a string where the characters that we need to remove are replaced by space characters.split() method on the output of the translate() method. After this step, we will get a list of substrings.join() method on an empty string. Here, we will pass the list of substrings as input to the join() method. join() method, we will get the desired string.You can observe the entire process in the following code.
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
translationTable = myStr.maketrans(charToDelete, " ")
outputString = "".join(myStr.translate(translationTable).split())
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
Regular expressions provide one of the most efficient ways to manipulate strings or text data.
To remove a character from a string, we can use the sub() method defined in the re module. The sub() method takes the character that needs to be replaced say old_char as its first input argument. It takes the new character new_char as its second input argument, and the input string as its third argument. After execution, it replaces the old_char with new_char in the input string and returns a new string.
To remove all the occurrences of a character from a given string, we will use the following steps.
old_char to the sub() method.new_char, we will pass an empty string.sub() method.After execution, the sub() method will return a new string. In the new string, the character that needs to be removed will get replaced by the empty string character. Hence, we will get the desired output string.
You can observe this in the following code.
import re
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = re.sub(charToDelete, "", myStr)
print("The modified string is:", outputString)
Output:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
In this article, we have discussed different ways to remove all the occurrences of a character from a list. Likewise, we have discussed different approaches to remove all the occurrences of a character in a string. For lists, I would suggest you use the approach with the remove() method. For strings, you can use either the replace() method or the re.sub() method as these are the most efficient approaches to remove all the occurrences of a character in a list or a string in python
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
The post Remove All Occurrences of a Character in a List or String in Python appeared first on PythonForBeginners.com.
]]>The post Convert String to Variable Name in Python appeared first on PythonForBeginners.com.
]]>We can convert a string to variable name in Python using the following functions.
If you just want to see how to change a string to a variable name in Python, you can directly jump to any implementation using the hyperlinks given above. However, I would suggest you read this article from the beginning to understand how these functions really work.
A variable in Python is a reference to an object in the memory. We use variables in Python to handle different types of values. When we assign a value to a Python variable, the interpreter creates a Python object for that value. After that, the variable name refers to the memory location. You can define a variable in Python as shown in the following Python program.
myVar = 5
print("The value in myVar is:", myVar)
Output:
The value in myVar is: 5
A Python string is a literal contained within single quotes or double quotes. We can also define strings using triple quotation marks.
We can define a string value and assign it to a string variable as shown in the following example.
myStr = "PythonForBeginners"
print("The value in myStr is:", myStr)
Output:
The value in myStr is: PythonForBeginners
In the above example, we have created a variable myStr. Then, we have assigned the string “PythonForBeginners” to myStr.
We can access the variable names in Python using the globals() function and the locals() function.
The globals() function, when executed, returns a Python dictionary that contains all the variable names as string literals and their corresponding values.
The dictionary is a global symbol table that contains all the names defined in the global scope of the program. You can observe this in the following Python code.
myStr = "PythonForBeginners"
myNum = 5
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
Output:
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fe3bfa934c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
In the above example, you can observe that the dictionary returned by the globals() function contains some default values as well as the variables defined by us.
The globals() function returns the dictionary that only contains the global variables as its key. When we define a variable inside a function or other inner scopes, we cannot access variables defined inside that scope using the globals() function.
For example, look at the following code.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f9d18bb24c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7f9d18b6f280>, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
Process finished with exit code 0
In the above example, we have defined funvar1 and funvar2 in the function myFun. However, these variables are not present in the global symbol table.
Even if we execute the globals() function in the function myFun, the variables defined in myFun won’t be included in the global symbol table. You can observe this in the following example.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
myStr = "PythonForBeginners"
myNum = 5
myFun()
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7eff3f70d4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7eff3f6ca280>, 'myStr': 'PythonForBeginners', 'myNum': 5}
To print the variable names defined inside a function, we can use the locals() function. The locals() function, when invoked inside a function or other inner scope, return a dictionary in which the variable names and their associated values are present as a key-value pair.
You can use the print statement to print the dictionary as shown below.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
print("The variables in local scope of myFun and their values are:")
myVars = locals()
print(myVars)
myStr = "PythonForBeginners"
myNum = 5
myFun()
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in local scope of myFun and their values are:
{'funvar1': 'Aditya', 'funVar2': 1117}
In the above example, you can observe that the dictionary returned by the locals() function contains the variables defined inside myFun.
The locals() function, when executed in the global scope, prints the dictionary containing global variables and their values. You can observe this in the following example.
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in the global scope and their values are:")
myVars = locals()
print(myVars)
Output:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in the global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd4fec2e4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7fd4febeb280>, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
Now that we have discussed how we can access variable names in Python, let us now discuss how we can create dynamic variables and define dynamic variable names in Python. For this, there are various ways that we will discuss one by one.
As we have seen in the previous section, the Python interpreter stores the variable names and their values in a symbol table in the form of a dictionary. If we are given a string as input in our program, we can define a variable name with the string by adding the input string as a key into the symbol table. We can add a single character, numeric values, or strings as the associated value to the variable.
To convert the string to a variable name, we will follow the following steps.
locals() function. The locals() function, when executed, returns the symbol table of the current scope.You can observe this using this simple example.
myStr = "domain"
print("The string is:",myStr)
myVars = locals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f2fb9cb44c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
In the above example, we have used the subscript notation to make changes to the symbol table. Instead of using the subscript notation to add the new string value as a key to the symbol table, you can use the __setitem__() method.
The __setitem__() method, when invoked on a python dictionary, takes a string literal as its first argument and the value associated with the new variable name as the second argument. After execution, the string and the value are added to the dictionary as a key-value pair in the dictionary.
As the symbol table returned by the locals() method is also a dictionary, we can use the __setitem__() method to convert a string to a variable name in Python as shown below.
myStr = "domain"
print("The string is:", myStr)
myVars = locals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f77830734c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
The above approach using the locals() method only makes the changes in the current scope, Therefore, it is useful when we want to convert a string to a variable name in a local scope like a function.
If you only want to change the symbol table of a function, you can use the locals() function to convert a string to a variable name in Python as follows.
def myFun():
myStr = "domain"
print("The string is:", myStr)
myVars = locals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
myFun()
Output:
The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}
If you want to make changes in the global symbol table to convert a Python string to a global variable name, you can execute the locals() function in the global scope. After that, you can add variables using the subscript notation or the __setitem__() method as shown in the previous examples.
If you want to convert a string to a global variable when you are inside a function, you cannot do it using the locals() function. For this task, you can use the globals() function.
When executed, the globals() function returns the global symbol table. You can make changes to the global symbol table inside any scope to convert a string to a global variable name. For this, we will perform the following steps.
globals() function. The globals() function, when executed, returns the global symbol table as a dictionary.After executing the above steps, we can convert a string to a global variable. You can observe this in the following example.
myStr = "domain"
print("The string is:",myStr)
myVars = globals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7ff717bd34c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
Instead of using the subscript notation, you can use the __setitem__() method with the globals() function to convert a string to a global variable name in Python as shown below.
myStr = "domain"
print("The string is:", myStr)
myVars = globals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fc4c62ba4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
Instead of using the locals() and the globals() function to convert a string to a variable name in Python, we can also use the vars() function.
The vars() function, when executed in the global scope, behaves just like the globals() function. When executed in a function or an inner scope, the vars() function behaves as the locals() function.
To convert a string into a variable name using the vars() function in the global scope, we will use the following steps.
vars() function, we will obtain the dictionary containing the variable names in the global scope. Following is the sample code that executes the above steps to convert a string to a variable name in Python.
myStr = "domain"
print("The string is:",myStr)
myVars = vars()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb9c6d614c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
You can also use the __setitem__() method on the dictionary instead of the subscript notation to create the variable as shown in the following example.
myStr = "domain"
print("The string is:", myStr)
myVars = vars()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
Output:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb5e21444c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
To convert a string to a variable name in a local scope like a function using the vars() function, you can execute the same steps that we used to create a global variable using the locals() function. You can observe this in the following example.
def myFun():
myStr = "domain"
print("The string is:", myStr)
myVars = vars()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
myFun()
Output:
The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}
In the previous sections, we have directly changed the symbol table to convert a string to a variable name. However, this is not the best way to perform the task.
Let us now discuss how we can convert a string to a variable name in python without directly changing the symbol table.
We can use the exec() function for the dynamic execution of a Python statement. The exec() function takes a Python statement in the form of a string as an input argument. Then, the Python statement is executed as if it were a normal Python statement written in the code.
For example, we can define a variable x with the value 5 using the exec() function as shown below.
myStr = "x=5"
exec(myStr)
print(x)
Output:
5
To convert a string to a variable name using the exec() function, we will use string formatting. We can do the entire process using the following steps.
exec() function. exec() function is executed, the variable will be created with the string myStr as the variable name.You can observe this in the following example.
myStr = "domain"
myVal = "pythonforbeginners.com"
myTemplate = "{} = \"{}\""
statement = myTemplate.format(myStr, myVal)
exec(statement)
print(domain)
Output:
pythonforbeginners.com
Instead of using the exec() function, we can also use the setattr() function to convert a string into a variable name in Python.
The setattr() function takes a Python object as its first input argument, the attribute (variable) name as the second input argument, and the value of the attribute as the third input argument. After execution, it adds the attribute to the object.
To convert a string to a variable name using the setattr() function, we first need to obtain the current scope as a Python object so that we can add the variable as an attribute to it. For this, we will have to perform two tasks.
To find the name of the modules that are currently loaded in the memory, we will use the sys.modules attribute. The sys.modules attribute contains a dictionary with mapping of module names to modules that have already been loaded.
After obtaining the dictionary, we need to find the current module. For this, we will use the __name__ attribute. __name__ is a built-in attribute that evaluates to the name of the current module.
The __name__ attribute is also present in the symbol table. You can find the name of the current module using the __name__ attribute as shown below.
print("The current module name is:")
print(__name__)
Output:
The current module name is:
__main__
Here, you can see that we are currently in the __main__ module.
After obtaining the name of the current module using the __name__ attribute, we will obtain the current module object using the subscript notation on sys.modules attribute.
After obtaining the current module, we will convert the string to a variable name using the setattr() function. For this, we will pass the current module as the first input argument, the string as the second input argument, and the value of the variable as the third input argument to the setattr() function. After execution of the setattr() function, the variable will be created in the current scope with the input string as the variable name.
You can observe this in the following example.
import sys
myStr = "domain"
myVal = "pythonforbeginners.com"
moduleName = __name__
currModule = sys.modules[moduleName]
setattr(currModule, myStr,myVal)
print(domain)
Output:
pythonforbeginners.com
In this article, we have discussed different ways to convert a string to a variable name in Python. Of all the approaches discussed in this article, I would suggest you use the approach with exec() method. This is so because there are several reserved keywords that we cannot use as a variable name. The keywords are used for different tasks to run the programs.
However, if we are directly changing the symbol table, it is possible that we might change the value associated with a keyword. In such as case, the program will run into an error. Therefore, try to use the approach with the exec() function to convert a string to a variable name in Python.
To learn more about python programming, you can read this article on tuple comprehension in Python. You might also like this article on if vs elif vs else in Python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
The post Convert String to Variable Name in Python appeared first on PythonForBeginners.com.
]]>The post Remove Commas From String in Python appeared first on PythonForBeginners.com.
]]>The simplest way to remove a comma from a string is to create a new string leaving the comma behind.
In this approach, we will first create an empty string newString. After that, we will traverse through the input string character by character using a for loop. While traversing, we will check if the current character is a comma or not. If the character is not a comma, we will add the present character to newString using the string concatenation operation. Once the execution of the for loop finishes, we will get the output string free from comma character in the variable newString.
You can observe this entire process in the following example.
myString = "This, is, a, string, that, has, commas, in, it."
print("Original String:", myString)
newString = ""
for character in myString:
if character != ",":
newString = newString + character
print("Output String:", newString)
Output:
Original String: This, is, a, string, that, has, commas, in, it.
Output String: This is a string that has commas in it.
Instead of traversing through the entire string to remove commas from the string, we can use the replace() method to remove commas from any given string.
The syntax of the replace method is as follows.
str.replace(old_character, new_character, count)
Here,
old_character is used to pass the character to the replace method that needs to be removed. We will remove the comma “,” as the first input argument.new_character is used to pass the character that will replace the old_character. We will pass an empty string as the new_character so that the comma character gets removed.old_character will be replaced by the new_character in the string. It is an optional parameter and we can leave it empty. In such a case, all the instances of old_character in the string will be replaced with new_character.replace() method returns the modified string after replacing all the instances of old_character with new_character.We can use the str.replace() method to remove commas from a given string as follows.
myString = "This, is, a, string, that, has, commas, in, it."
print("Original String:", myString)
newString = myString.replace(",", "")
print("Output String:", newString)
Output:
Original String: This, is, a, string, that, has, commas, in, it.
Output String: This is a string that has commas in it.
Regular expressions are a great tool to manipulate strings. We can also use them to remove commas from a string in python. For this, we will use the re.sub() method.
The syntax for re.sub() method is as follows.
re.sub(old_character, new_character, input_string)
Here,
old_character is used to pass the character to the re.sub() method that needs to be removed. We will remove the comma “,” as the first input argument.new_character is used to pass the character that will replace the old_character. We will pass an empty string as the new_character so that the comma character gets removed.input_string parameter is used to pass the string that needs to be modified to the re.sub() method .We can use the re.sub() method to remove commas from a given string as follows.
import re
myString = "This, is, a, string, that, has, commas, in, it."
print("Original String:", myString)
newString = re.sub(",", "", myString)
print("Output String:", newString)
Output:
Original String: This, is, a, string, that, has, commas, in, it.
Output String: This is a string that has commas in it.
In this article, we have discussed three ways to remove commas from a string in python. To know more about strings in python, you can read this article on regular expressions in python. You might also like this article on list comprehension in python.
The post Remove Commas From String in Python appeared first on PythonForBeginners.com.
]]>The post String Indexing in Python appeared first on PythonForBeginners.com.
]]>If we have an ordered sequence or container object such as a string, a list, or a tuple, we can access the elements of the objects using their relative position in the sequence. The relative position of the elements in the ordered sequence is termed as index. With Indexing, we can access any element from an ordered sequence using the indices.
In python, string indexing is zero based. It means that we start the counting from 0 and the first character of the string is assigned the index 0, the second character is assigned the index 1, the third character is assigned the index 2 and so on.
We can understand this using the following example.
Suppose that we have a string “PythonForBeginners”
Here, the index of the letter “P” is 0. The index of the letter “y” is 1. The index of letter ”t” is 2, The index of letter “h” is 3 and so on. The index of the last letter “s” is 17.
In python, we can use positive as well as negative numbers for string indexing. Let us discuss them one by one.
As we have seen above, Strings are indexed using positive numbers from 0 to string length -1. We can access a character at any position between 0 to (length of the string) -1 using positive indices as follows.
myString = "PythonForbeginners"
index = 0
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 1
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 2
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 3
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 17
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
Output:
Character at index 0 in the string 'PythonForbeginners' is P.
Character at index 1 in the string 'PythonForbeginners' is y.
Character at index 2 in the string 'PythonForbeginners' is t.
Character at index 3 in the string 'PythonForbeginners' is h.
Character at index 17 in the string 'PythonForbeginners' is s.
Always remember that an index greater than or equal to the string length will cause an IndexError exception as follows.
myString = "PythonForbeginners"
index = 20
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
character = myString[index]
IndexError: string index out of range
You can either avoid the IndexError exception by checking the value of index before accessing any character in the string. Alternatively, you can use python try except block to handle the exceptions if they occur.
Here, I will suggest you to use the try except blocks. Checking the index every time we access a character may be redundant and costly if we are accessing using indices less than the length of the string. While using try except blocks, the program will not check the value of index each time we access a character from the string. If IndexError occurs, it will be handled by the code in the except block.
We can also use negative indices for accessing characters from a string. In python, the last character of the string is assigned an index -1. The second last character is assigned an index -2. Similarly, the first character of the string is assigned an index -(length of the string).
We can understand this using the following example.
Suppose that we have a string “PythonForBeginners”
Here, the index of the letter “s” is -1. The index of the letter “r” is -2. The index of letter ”n” is -3 , The index of letter “n” is -4 and so on. The index of the first letter “P” is -18.
You can verify this using the following program.
myString = "PythonForbeginners"
index = -1
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -2
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -3
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -4
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -18
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
Output:
Character at index -1 in the string 'PythonForbeginners' is s.
Character at index -2 in the string 'PythonForbeginners' is r.
Character at index -3 in the string 'PythonForbeginners' is e.
Character at index -4 in the string 'PythonForbeginners' is n.
Character at index -18 in the string 'PythonForbeginners' is P.
While using negative numbers as indices, Make sure that you do not pass an index less than -(length of the string). Otherwise, your program will run into an IndexError as follows.
myString = "PythonForbeginners"
index = -20
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
Output:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
character = myString[index]
IndexError: string index out of range
In this article, we have studied string indexing in python. We have seen how we can use negative as well as positive numbers to access characters from a string. To study more about strings in python, you can read this article on string concatenation.
The post String Indexing in Python appeared first on PythonForBeginners.com.
]]>The post String Slicing in Python appeared first on PythonForBeginners.com.
]]>String slicing is the process of taking out a part of a string. The characters in the extracted part may be continuous or they may be present at regular intervals in the original string.
You can understand string slicing using the following analogy.
Suppose that you are slicing a loaf of bread into pieces. All the pieces, whatever be their thickness,constitute a slice of the bread. Similarly, We can create slices from a string. The only difference in this analogy is that in case of slicing of bread,the original bread is destroyed after the formation of slices. On the contrary, while slicing a string, the original string remains as it is even after creating new slices.
Let us take an example. Suppose that we have a string “Pythonforbeginners”.
Different slices of the string can be as follows:
In python there are two ways to create slices of a string. We can create a slice from a string using indexing as well as the built-in slice() method. Let us discuss both the methods one by one.
We can create a slice from a string using indices of the characters. The syntax for string slicing using indices is string_name [ start_index:end_index:step_size ]. Here,
We can understand the working of the above syntax using the following example.
myString = "Pythonforbeginners"
mySlice = myString[0:6:1]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 5, 1, mySlice))
mySlice = myString[13:8:-1]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 13, 9, -1, mySlice))
mySlice = myString[0:8:2]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 8, 2, mySlice))
mySlice = myString[18:7:-3]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 18, 7, -3, mySlice))
Output:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 and step size 1 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at index 9 and step size -1 is 'nigeb'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 8 and step size 2 is 'Ptof'
Slice of string 'Pythonforbeginners' starting at index 18, ending at index 7 and step size -3 is 'sngr'
An alternate syntax for string slicing is that we specify only start_index and end_index as in string_name [ start_index:end_index]. Here, the step_size is taken as 1 and the characters are selected consecutively from start_index to end_index-1 as follows.
myString = "Pythonforbeginners"
mySlice = myString[0:6]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
Output:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'Python'
We can also opt to not specify the start_index and the end_index. In such cases, the default value of start_index is taken as 0 and the default value of end_index is taken as length of the string. You can observe these variations in the following example.
myString = "Pythonforbeginners"
mySlice = myString[:6]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
mySlice = myString[13:]
print("Slice of string '{}' starting at index {}, ending at last index is '{}'".format(myString, 13, mySlice))
Output:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at last index is 'nners'
Instead of using indices of the character directly, we can use the slice() method. The slice() method takes the start_index, end_index and step_size as input and creates a slice object. The slice object is then passed to the original string as index, which then creates the slice of the original string as follows.
myString = "Pythonforbeginners"
slice_obj = slice(0, 6, 1)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 5, 1,
mySlice))
slice_obj = slice(13, 8, -1)
mySlice = myString[slice_obj]
print(
"Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 13, 9, -1,
mySlice))
slice_obj = slice(0, 8, 2)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 8, 2,
mySlice))
slice_obj = slice(18, 7, -3)
mySlice = myString[slice_obj]
print(
"Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 18, 7, -3,
mySlice))
Output:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 and step size 1 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at index 9 and step size -1 is 'nigeb'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 8 and step size 2 is 'Ptof'
Slice of string 'Pythonforbeginners' starting at index 18, ending at index 7 and step size -3 is 'sngr'
You can see that the slice object works in almost the same way that we have used to create a slice from a string using the indices of the characters. You can understand this more clearly using the following examples.
myString = "Pythonforbeginners"
# specify only start and end index
slice_obj = slice(5, 16)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
# specify only end index
slice_obj = slice(12)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 12, mySlice))
Output:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'nforbeginne'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 12 is 'Pythonforbeg'
In this article, we have discussed string slicing in python. We have also looked at different ways to create slices from a given string. To study more about strings in python, you can read this article on string concatenation.
The post String Slicing in Python appeared first on PythonForBeginners.com.
]]>The post String to Integer in Python appeared first on PythonForBeginners.com.
]]>We can use int() function to convert a string to integer in Python. The string which has to be converted to integer is passed to the int() function as input argument and the function returns the corresponding integer value if the string passed as input is in proper format and no error occurs during conversion of the string to integer. We can convert a string to integer using int() function as follows.
print("Input String is:")
myInput= "1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
1117
Output Integer is:
1117
When the input string is not in correct format, the int() function raises ValueError. This can be seen in the following example.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
aditya1117
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-3-c8793975130e>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: 'aditya1117'
There may be several cases in which int() function will raise ValueError while converting a string to integer. Some of the cases are discussed below.
When we pass a string containing alphabets instead of numeric literals, ValueError will occur and input string will not be converted to integer. This can be seen in the following example.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
aditya1117
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-10-c8793975130e>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int()
When the passed string contains any space characters along with numeric literals, ValueError will occur and input string will not be converted to integer. This can be seen in the following example.
print("Input String is:")
myInput= "11 17"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
11 17
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-4-46d411efb04b>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '11 17'
When the passed string contains any punctuation marks such as period character (.) or comma (,) along with numeric literals, ValueError will occur and input string will not be converted to integer. This can be seen in the following example.
print("Input String is:")
myInput= "11.17"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
Output:
Input String is:
11.17
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-5-97993fa7ba5b>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '11.17'
While converting a string to integer in Python, we can either preemptively check if the passed string consists of only the digits or not so that we can avoid the occurrence of error or we can use Python try except to handle the ValueError after it has been raised by the int() function. Both the methods have been discussed below.
We can use the isdigit() method to check if a string consists of only numeric characters or not. The isdigit() method when invoked on a string returns true if the string consists of only numeric digits. Otherwise it returns false. This can be implemented as follows.
print("Input String is:")
myInput= "1117"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
Output:
Input String is:
1117
Output Integer is:
1117
If the input string contains characters other than numbers, output will be as follows.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
Output:
Input String is:
aditya1117
Input cannot be converted into integer.
To handle the ValueError after it has occurred, we can use exception handling using Python try except to handle the ValueError and show a proper message to the user as follows.
print("Input String is:")
myInput= "1117"
print(myInput)
try:
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
Output:
Input String is:
1117
Output Integer is:
1117
If the input string contains characters other than numbers, output will be as follows.
print("Input String is:")
myInput= "aditya1117"
print(myInput)
try:
myInt=int(myInput)
print("Output Integer is:")
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
Output:
Input String is:
aditya1117
Input cannot be converted into integer.
In this article, we have seen how we can convert a string to integer in Python and what problems can occur during conversion. We have also seen how to avoid and handle the ValueError raise by int() function during conversion of string to integer. Stay tuned for more informative articles.
The post String to Integer in Python appeared first on PythonForBeginners.com.
]]>