Python Strings Category Page - PythonForBeginners.com https://www.pythonforbeginners.com Learn By Example Fri, 30 Jun 2023 13:02:40 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.13 https://www.pythonforbeginners.com/wp-content/uploads/2020/05/cropped-pfb_icon-32x32.png Python Strings Category Page - PythonForBeginners.com https://www.pythonforbeginners.com 32 32 201782279 Split a number in a string in Python https://www.pythonforbeginners.com/python-strings/split-a-number-in-a-string-in-python Thu, 01 Apr 2021 13:28:56 +0000 https://www.pythonforbeginners.com/?p=8616 While processing text data, it may be a situation that we have to extract numbers from the text data. In python, we process text data using strings. So, the task we have to do is to find and split a number in a string. While extracting the numbers, we can classify the string into two […]

The post Split a number in a string in Python appeared first on PythonForBeginners.com.

]]>
While processing text data, it may be a situation that we have to extract numbers from the text data. In python, we process text data using strings. So, the task we have to do is to find and split a number in a string. While extracting the numbers, we can classify the string into two types. The first type will contain only numbers which are space separated and the second type of strings will also contain alphabets and punctuation marks along with the numbers. In this article, we will see how we can extract numbers from both the types of strings one by one. So, let’s dive into it.

Split a number in a string when the string contains only space separated numbers.

When the string contains only space separated numbers in string format, we can simply split the string at the spaces using python string split operation. The split method when invoked on any string returns a list of sub strings which will be numbers in string format in our case. After getting the numbers in the string format in the list, we can convert all the strings to integers using int() function. This can be done as follows. 


num_string="10 1 23 143 234 108 1117"
print("String of numbers is:")
print(num_string)
str_list=num_string.split()
print("List of numbers in string format is:")
print(str_list)
num_list=[]
for i in str_list:
    num_list.append(int(i))    
print("Output List of numbers is:")
print(num_list)

Output:

String of numbers is:
10 1 23 143 234 108 1117
List of numbers in string format is:
['10', '1', '23', '143', '234', '108', '1117']
Output List of numbers is:
[10, 1, 23, 143, 234, 108, 1117]

We can also perform the above operation using list comprehension as follows.


num_string="10 1 23 143 234 108 1117"
print("String of numbers is:")
print(num_string)
str_list=num_string.split()
print("List of numbers in string format is:")
print(str_list)
num_list=[int(i) for i in str_list]   
print("Output List of numbers is:")
print(num_list)

Output:

String of numbers is:
10 1 23 143 234 108 1117
List of numbers in string format is:
['10', '1', '23', '143', '234', '108', '1117']
Output List of numbers is:
[10, 1, 23, 143, 234, 108, 1117]

We can also use map() function to convert the strings in the list to integers. The map() function takes as input a function and an iterable as argument and executes the function on each element of the iterable object and returns  the output map object which can be converted into any iterable. Here we will provide the int() function as first argument and the list of strings as second argument so that the strings can be converted to integers. This can be done as follows.

num_string="10 1 23 143 234 108 1117"
print("String of numbers is:")
print(num_string)
str_list=num_string.split()
print("List of numbers in string format is:")
print(str_list)
num_list=list(map(int,str_list))
print("Output List of numbers is:")
print(num_list)

Output:

String of numbers is:
10 1 23 143 234 108 1117
List of numbers in string format is:
['10', '1', '23', '143', '234', '108', '1117']
Output List of numbers is:
[10, 1, 23, 143, 234, 108, 1117]

 Split a number in a string when the string contains Alphabets.

When the string contains alphabets, we will first extract the numbers out of the string using regular expressions and then we will convert the numbers to integer form.

For extracting the numbers, we will use findall() method from re module. re.findall() takes the pattern (one or more digits in our case)  and string as input and returns the list of substrings where the pattern is matched. After extracting the list of numbers in the form of string, we can convert the strings into integers as follows.


import re
num_string="I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117"
print("Given String is:")
print(num_string)
pattern="\d+"
str_list=re.findall(pattern,num_string)
print("List of numbers in string format is:")
print(str_list)
num_list=[]
for i in str_list:
    num_list.append(int(i)) 
print("Output List of numbers is:")
print(num_list)

Output:

Given String is:
I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117
List of numbers in string format is:
['20', '102', '23', '120', '1117']
Output List of numbers is:
[20, 102, 23, 120, 1117]

We can use list comprehension to perform the above operation as follows.

import re
num_string="I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117"
print("Given String is:")
print(num_string)
pattern="\d+"
str_list=re.findall(pattern,num_string)
print("List of numbers in string format is:")
print(str_list)
num_list=[int(i) for i in str_list]
print("Output List of numbers is:")
print(num_list)

Output:

Given String is:
I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117
List of numbers in string format is:
['20', '102', '23', '120', '1117']
Output List of numbers is:
[20, 102, 23, 120, 1117]

We can perform the same operation using map() function as follows.



import re
num_string="I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117"
print("Given String is:")
print(num_string)
pattern="\d+"
str_list=re.findall(pattern,num_string)
print("List of numbers in string format is:")
print(str_list)
num_list=list(map(int,str_list))
print("Output List of numbers is:")
print(num_list)

Output:

Given String is:
I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117
List of numbers in string format is:
['20', '102', '23', '120', '1117']
Output List of numbers is:
[20, 102, 23, 120, 1117]

Conclusion

In this article, we have seen how to split a number in a string and extract it into another list using different methods like list comprehension and regular expressions. Stay tuned for more informative articles.

The post Split a number in a string in Python appeared first on PythonForBeginners.com.

]]>
8616
How to Join Strings in Python 3 https://www.pythonforbeginners.com/python-strings/how-to-join-strings-in-python-3 Wed, 17 Mar 2021 21:49:15 +0000 https://www.pythonforbeginners.com/?p=8412 Programmers are destined to work with plenty of string data. This is partially because computer languages are tied to human language, we use one to create the other, and vice versa.  For this reason, it’s a good idea to master the ins and outs of working with strings early on. In Python, this includes learning […]

The post How to Join Strings in Python 3 appeared first on PythonForBeginners.com.

]]>
Programmers are destined to work with plenty of string data. This is partially because computer languages are tied to human language, we use one to create the other, and vice versa. 

For this reason, it’s a good idea to master the ins and outs of working with strings early on. In Python, this includes learning how to join strings.

Manipulating strings may seem daunting, but the Python language includes tools that make this complex task easier. Before diving into Python’s toolset, let’s take a moment to examine the properties of strings in Python.

A Little String Theory

As you may recall, in Python, strings are an array of character data.

An important point about strings is that they are immutable in the Python language. This means that once a Python string is created, it cannot be changed. Changing the string would require creating an entirely new string, or overwriting the old one. 

We can verify this feature of Python by creating a new string variable. If we try to change a character in the string, Python will give us a Traceback Error.

>>> my_string = "Python For Beginners"
>>> my_string[0]
'P'
>>> my_string[0] = 'p'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Its a good idea to keep the immutable quality of strings in mind when writing Python code. 

While you can’t change strings in Python, you can join them, or append them. Python comes with many tools to make working with strings easier.

In this lesson, we’ll cover various methods for joining strings, including string concatenation. When it comes to joining strings, we can make use of Python operators as well as built-in methods. 

As students progress, they’re likely to make use of each of these techniques in one way or another. Each has their own purpose.

Joining Strings with the ‘+’ Operator

Concatenation is the act of joining two or more strings to create a single, new string.

In Python, strings can be concatenated using the ‘+’ operator. Similar to a math equation, this way of joining strings is straight-forword, allowing many strings to be “added” together. 

Let’s take a look at some examples:

# joining strings with the '+' operator
first_name = "Bilbo"
last_name = "Baggins"

# join the names, separated by a space
full_name = first_name + " " + last_name

print("Hello, " + full_name + ".")

In our first example, we created two strings, first_name and last_name, then joined them using the ‘+’ operator. For clarity, we added space between the names.

Running the file, we see the following text in the Command Prompt:

Hello, Bilbo Baggins.

The print statement at the end of the example shows how joining strings can generate text that is more legible. By adding punctuation through the power of concatenation, we can create Python programs that are easier to understand, easier to update, and more likely to be used by others.

Let’s look at another example. This time we’ll make use of a for loop to join our string data.

# some characters from Lord of the Rings
characters = ["Frodo", "Gandalf", "Sam", "Aragorn", "Eowyn"]

storyline = ""

# loop through each character and add them to the storyline
for i in range(len(characters)):
    # include "and" before the last character in the list
    if i == len(characters)-1:
        storyline += "and " + characters[i]
    else:
        storyline += characters[i] + ", "

storyline += " are on their way to Mordor to destroy the ring."

print(storyline)

This more advanced example shows how concatenation can be used to generate human readable text from a Python list. Using a for loop, the list of characters (taken from the Lord of the Rings novels) is, one-by-one, joined to the storyline string. 

A conditional statement was included inside this loop to check whether or not we’ve reached the last object in the list of characters. If we have, an additional “and” is included so that the final text is more legible. We’re also sure to include our oxford commas for additional legibility.

Here’s the final output:

Frodo, Gandalf, Sam, Aragorn, and Eowyn, are on their way to Mordor to destroy the ring.

This method will NOT work unless both objects are stings. For instance, trying to join a string with a number will produce an error.

>>> string = "one" + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

As you can see, Python will only let us concatenate a string to another string. It’s our jobs as programmers to understand the limitations of the languages we’re working with. In Python, we’ll need to make sure we’re concatenating the correct types of objects if we wish to avoid any errors.

Joining Lists with the ‘+’ Operator

The ‘+’ operator can also be used to join one or more lists of string data. For instance, if we had three lists, each with their own unique string, we could use the ‘+’ operator to create a new list combining elements from all three.

hobbits = ["Frodo", "Sam"]
elves = ["Legolas"]
humans = ["Aragorn"]

print(hobbits + elves + humans)

As you can see, the ‘+’ operator has many uses. With it, Python programmers can easily combine string data, and lists of strings.

Joining Strings with the .join() Method

If you’re dealing with an iterable object in Python, chances are you’ll want to use the .join() method. An iterable object, such as a string or a list, can be easily concatenated using the .join() method. 

Any Python iterable, or sequence, can be joined using the .join() method. This includes, lists and dictionaries. 


The .join() method is a string instance method. The syntax is as follows:

string_name.join(iterable)

Here’s an example of using the .join() method to concatenate a list of strings:

numbers = ["one", "two", "three", "four", "five"]

print(','.join(numbers))

Running the program in the command prompt, we’ll see the following output:

one,two,three,four,five

The .join() method will return a new string that includes all the elements in the iterable, joined by a separator. In the previous example, the separator was a comma, but any string can be used to join the data.

numbers = ["one", "two", "three", "four", "five"]
print(' and '.join(numbers))

We can also use this method to join a list of alphanumeric data, using an empty string as the separator.

title = ['L','o','r','d',' ','o','f',' ','t','h','e',' ','R','i','n','g','s']
print(“”.join(title))

The .join() method can also be used to get a string with the contents of a dictionary. When using .join() this way, the method will only return the keys in the dictionary, and not their values.

number_dictionary = {"one":1, "two":2, "three":3,"four":4,"five":5}
print(', '.join(number_dictionary))

When joining sequences with the .join() method, the result will be a string with elements from both sequences.

Copying Strings with ‘*’ Operator

If you need to join two or more identical strings, it’s possible to use the ‘*’ operator. 

With the ‘*’ operator, you can repeat a string any number of times.

fruit = “apple”
print(fruit * 2)

The ‘*’ operator can be combined with the ‘+’ operator to concatenate strings. Combining these methods allows us to take advantage of Python’s many advanced features.

fruit1 = "apple"
fruit2 = "orange"

fruit1 += " "
fruit2 += " "

print(fruit1 * 2 + " " + fruit2 * 3)

Splitting and Rejoining Strings

Because strings in Python are immutable, it’s quite common to split and rejoin them. 

The .split() method is another string instance method. That means we can call it off the end of any string object. 

Like the .join() method, the .split() method uses a separator to parse the string data. By default, whitespace is used as the separator for this method.

Let’s take a look at the .split() method in action.

names = "Frodo Sam Gandalf Aragorn"

print(names.split())

This code outputs a list of strings.

['Frodo', 'Sam', 'Gandalf', 'Aragorn']

Using another example, we’ll see how to split a sentence into its individual parts.

story = "Frodo took the ring of power to the mountain of doom."
words = story.split()
print(words)

Using the .split() method returns a new iterable object. Because the object is iterable, we can use the .join() method we learned about earlier to “glue” the strings back together.

original = "Frodo took the ring of power to the mountain of doom."
words = original.split()

remake = ' '.join(words)
print(remake)

By using string methods in Python, we can easily split and join strings. These methods are crucial to working with strings and iterable objects.

Tying Up the Loose Ends

By now, you should have a deeper knowledge of strings and how to use them in Python 3. Working through the examples provided in this tutorial will be a great start on your journey to mastering Python.

No student, however, can succeed alone. That’s why we’ve compiled a list of additional resources provided by Python For Beginners to help you complete your training.

With help, and patience, anyone can learn the basics of Python. If working to join strings in Python seems daunting, take some time to practice the examples above. By familiarizing yourself with string variables, and working with methods, you’ll quickly tap into the unlimited potential of the Python programming language.

The post How to Join Strings in Python 3 appeared first on PythonForBeginners.com.

]]>
8412
How to remove punctuation from a Python String https://www.pythonforbeginners.com/python-strings/how-to-remove-punctuation-from-a-python-string Tue, 16 Mar 2021 20:12:56 +0000 https://www.pythonforbeginners.com/?p=8437 Often during data analysis tasks, we come across text data which needs to be processed so that useful information can be derived from the data. During text processing, we may have to extract or remove certain text from the data to make it useful or we may also need to replace certain symbols and terms […]

The post How to remove punctuation from a Python String appeared first on PythonForBeginners.com.

]]>
Often during data analysis tasks, we come across text data which needs to be processed so that useful information can be derived from the data. During text processing, we may have to extract or remove certain text from the data to make it useful or we may also need to replace certain symbols and terms with other text to extract useful information. In this article, we will study about punctuation marks and will look at the methods to remove punctuation marks from python strings.

What is a punctuation mark?

There are several symbols in English grammar which include comma, hyphen, question mark, dash, exclamation mark, colon, semicolon, parentheses, brackets etc which are termed as punctuation marks. These are used in English language for grammatical purposes but when we perform text processing in python we generally have to omit the punctuation marks from our strings. Now we will see different methods to remove punctuation marks from a string in Python.

Removing punctuation marks from string using for loop

In this method,first we will create an empty python string which will contain the output string. Then we will simply iterate through each character of the python string and check if it is a punctuation mark or not. If the character will be a punctuation mark, we will leave it. Otherwise we will include it in our output string using string concatenation.

For Example, In the code given below, we have each punctuation mark kept in a string named punctuation. We iterate through the input string myString using for loop and then we check if the character is present in the punctuation string or not. If it is not present, the character is included in the output string newString .


punctuation= '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
print("The punctuation marks are:")
print(punctuation)
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
newString=""
for x in myString:
    if x not in punctuation:
        newString=newString+x
print("Output String is:")
print(newString)

Output

The punctuation marks are:
!()-[]{};:'"\, <>./?@#$%^&*_~
Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners

Remove punctuation marks from python string using regular expressions

We can also remove punctuation marks from strings in python using regular expressions. For this we will use re module in python which provides functions for processing strings using regular expressions.

In this method, we will substitute each character which is not an alphanumeric or space character by an empty string using re.sub() method  and hence all of the punctuation will be removed.

The syntax for sub() method is re.sub(pattern1, pattern2,input_string) where pattern1 denotes the pattern of the characters which will be replaced. In our case, we will provide a pattern which denotes characters which  is not an alphanumeric or space character. pattern2 is the final pattern by which characters in pattern1 will be replaced. In our case pattern2 will be empty string as we just have to remove the punctuation marks from our python string. input_string is the string which has to be processed to remove punctuation.

Example:


import re
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
emptyString=""
newString=re.sub(r'[^\w\s]',emptyString,myString)
print("Output String is:")
print(newString)

Output

Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners

Remove punctuation marks from python string using replace() method

Python string replace() method takes initial pattern and final pattern as parameters when invoked on a string and returns a resultant string where characters of initial pattern are replaced by characters in final pattern.

We can use replace() method to remove punctuation from python string by replacing each punctuation mark by empty string. We will iterate over the entire punctuation marks one by one replace it by an empty string in our text string.

The syntax for replace() method is replace(character1,character2) where character1 is the character which will be replaced by given character in the parameter character2. In our case, character1 will contain punctuation marks and character2 will be an empty string.


punctuation= '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
emptyString=""
for x in punctuation:
    myString=myString.replace(x,emptyString)
print("Output String is:")
print(myString)

Output:

Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners

Remove punctuation marks from python string using translate() method

The translate() method replaces characters specified in the input string with new characters according to the translation table provided to the function as parameter. The translation table should contain the mapping of which characters have to be replaced by which characters. If the table does not have the mapping for any character, the character will not be replaced.

The syntax for translate() method is translate(translation_dictionary) where the translation_dictionary will be a python dictionary containing mapping of characters in the input string to the characters by which they will be replaced.

To create the translation table, we can use maketrans() method. This method takes the initial characters to be replaced, final characters and characters to be deleted from the string in the form of string as optional input and returns a python dictionary which works as translation table.

The syntax for maketrans() method is maketrans(pattern1,pattern2,optional_pattern). Here pattern1 will be a string containing all the characters which are to be replaced. pattern2 will be a string containing the characters by which characters in pattern1 will be replaced. Here the length of pattern1 should be equal to length of pattern2. optional_pattern is a string containing the characters which have to be deleted from the input text. In our case, pattern1 and pattern2 will be empty strings while optional_pattern will be a string containing punctuation marks.

To create a translation table for removing punctuation from python string, we can leave empty the first two parameters of maketrans() function and include the punctuation marks in the list of characters to be excluded. In this way all the punctuation marks will be deleted and output string will be obtained.

Example

punctuation= '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
myString= "Python.:F}or{Beg~inn;ers"
print("Input String is:")
print(myString)
emptyString=""
translationTable= str.maketrans("","",punctuation)
newString=myString.translate(translationTable)
print("Output String is:")
print(newString)

Output

Input String is:
Python.:F}or{Beg~inn;ers
Output String is:
PythonForBeginners

Conclusion

In this article, we have seen how to remove punctuation marks from strings in python using for loop , regular expressions and inbuilt string methods like replace() and translate(). Stay tuned for more informative articles.

The post How to remove punctuation from a Python String appeared first on PythonForBeginners.com.

]]>
8437
String Splicing in Python https://www.pythonforbeginners.com/python-strings/string-splicing-in-python Tue, 09 Mar 2021 08:20:35 +0000 https://www.pythonforbeginners.com/?p=8428 Python strings are sequences of characters enclosed in single, double or triple quotes. Strings are immutable in python. We can access each character of a string using string splicing in python. Splicing is also termed as indexing. What is String Splicing in Python? String splicing or indexing is a method by which we can access […]

The post String Splicing in Python appeared first on PythonForBeginners.com.

]]>
Python strings are sequences of characters enclosed in single, double or triple quotes. Strings are immutable in python. We can access each character of a string using string splicing in python. Splicing is also termed as indexing.

What is String Splicing in Python?

String splicing or indexing is a method by which we can access any character or group of characters from a python string. In python, characters or sub strings of a string can be accessed with the help of square brackets [ ] just like we access elements from a list in python. We can access a character from a string using positive indices as well as negative indices.

When using positive indices for string splicing in python, the first character of the string is given index zero and the index of subsequent characters are increased by 1 till end.

For example, we can print first character, third character and eleventh character of an string using the following program. Note that indexing is 0 based in python. i.e. first character is given the index 0 and not 1.

myString="PythonForBeginners"
x=myString[0]
print(x)
x=myString[2]
print(x)
x=myString[10]
print(x)

Output

P
t
e

When using negative indices for string splicing in python, the last character of the python string is given index -1 and moving backwards, each character is given index 1 less than its previous character.

In the following example, we use negative indexing for printing characters of a python string.

myString="PythonForBeginners"
x=myString[-1]
print(x)
x=myString[-5]
print(x)
x=myString[-10]
print(x)

Output

s
n
r

How to capture a sub string from a python string?

A sub string is a continuous part of a python string. It may start from any index and end at any index. 

Using positive indexing, we can capture a sub string using square brackets [ ] operator. We can specify the index of the starting character and index of the final character of the string which is to be included in sub string. The syntax for taking out the sub string is string_name[start_index:last_index]. The character at start_index is included in the sub string but the character at last_index is not included. Only characters till index last_index-1 are included. Hence start_index is inclusive while last_index is exclusive.

In the examples given below, we can see that characters at start_index have been included in the output and characters at last_index have not been included in the output.


myString="PythonForBeginners"
x=myString[0:5]
print(x)
x=myString[6:9]
print(x)
x=myString[0:6]
print(x)

Output

Pytho
For
Python

To capture a sub string from starting to a given index we can leave empty the start_index value.

myString="PythonForBeginners"
x=myString[:6]
print(x)
x=myString[:9]
print(x)
x=myString[:18]
print(x)

Output

Python
PythonFor
PythonForBeginners

To capture a string starting at a given index and ending at last index, we can simply leave the last_index value empty.

myString="PythonForBeginners"
x=myString[0:]
print(x)
x=myString[6:]
print(x)
x=myString[9:]
print(x)

Output

PythonForBeginners
ForBeginners
Beginners

We can also capture sub strings from python strings using negative indices in the same way as above.

myString="PythonForBeginners"
x=myString[-10:-1]
print(x)
x=myString[:-1]
print(x)
x=myString[-5:-1]
print(x)

Output

rBeginner
PythonForBeginner
nner

The sub strings in python also strings and we can perform operations like string concatenation, python string split e.t.c.

For example, we can perform string concatenation as shown in the following example.


myString="PythonForBeginners"
x1=myString[:6]
x2=myString[6:9]
x3=myString[9:]

x=x1+x2+x3
print(x)

Output:

PythonForBeginners

How to capture a sub sequence from python string?

A sub sequence of a python string is a sequence of characters which are taken out from the string without disturbing the order in which the characters are present in the string. The characters in the sub sequence may or may not be continuous characters of the input python string.

To capture a sub sequence, we use the square bracket [ ] operator. The syntax for capturing a sub sequence from a string is string_name[start_index,end_index,difference]. difference denotes the number to be added to start_index to get index of next character to be included in sub sequence and difference-1 characters are skipped after a character is included in the sub sequence.

myString="PythonForBeginners"
x=myString[0:10:2]
print(x)
x=myString[0:10:3]
print(x)

Output

PtoFr
PhFB

Conclusion

In this article, we have studied about string splicing in python. We have also seen how to capture sub strings and sub sequences from a python string using string splicing. Stay tuned for more informative articles.

The post String Splicing in Python appeared first on PythonForBeginners.com.

]]>
8428
How to use Split in Python https://www.pythonforbeginners.com/dictionary/python-split https://www.pythonforbeginners.com/dictionary/python-split#comments Tue, 09 Jun 2020 05:07:00 +0000 https://www.pythonforbeginners.com/?p=814 Learn how to use split in python. Definition The split() method splits a string into a list using a user specified separator. When a separator isn’t defined, whitespace(” “) is used. Why use the Split() Function? At some point, you may need to break a large string down into smaller chunks, or strings. This is […]

The post How to use Split in Python appeared first on PythonForBeginners.com.

]]>
Learn how to use split in python.

Quick Example: How to use the split function in python

  1. Create an array

    x = ‘blue,red,green’

  2. Use the python split function and separator

    x.split(“,”) – the comma is used as a separator. This will split the string into a string array when it finds a comma.

  3. Result

    [‘blue’, ‘red’, ‘green’]

Definition

The split() method splits a string into a list using a user specified separator. When a separator isn’t defined, whitespace(” “) is used.

Why use the Split() Function?

At some point, you may need to break a large string down into smaller chunks, or strings. This is the opposite of concatenation which merges or combines strings into one.

To do this, you use the python split function. What it does is split or breakup a string and add the data to a string array using a defined separator.

If no separator is defined when you call upon the function, whitespace will be used by default. In simpler terms, the separator is a defined character that will be placed between each variable.

Examples of the Python Split Function In Action

Let’s take a look at some examples.

x = ‘blue,red,green
x.split(“,”)
 
[‘blue’, ‘red’, ‘green’]
>>>
 
>>> a,b,c = x.split(“,”)
 
>>> a
‘blue’
 
>>> b 
‘red’
 
>>> c
‘green’

As you can see from this code, the function splits our original string which includes three colors and then stores each variable in a separate string. This leaves us with three strings of “a”, “b”, and “c”. Then, when you ask the interpreter to spit out the variables stored in these strings, you get the appropriate color.

Pretty neat, no? It’s also extremely useful when you’re working extensively with strings and variables.

Let’s look at another example.

>>> words = “This is random text we’re going to split apart”
 
>>> words2 = words.split(“ “)
 
>>> words2

[‘This’, ‘is’, ‘random’, ‘text’, ‘we’re’, ‘going’, ‘to’, ‘split’, ‘apart’]

What we did here is split the larger string and store the variables as a list under the “words2” string.

The post How to use Split in Python appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/dictionary/python-split/feed 1 814
String Manipulation in Python https://www.pythonforbeginners.com/basics/string-manipulation-in-python https://www.pythonforbeginners.com/basics/string-manipulation-in-python#comments Tue, 09 Apr 2013 08:55:18 +0000 https://www.pythonforbeginners.com/?p=4968 We use strings in Python to handle text data. In this article, we will discuss basics of python strings and string manipulation in Python. What’s a String in Python? A python string is a list of characters in an order. A character is anything you can type on the keyboard in one keystroke, like a […]

The post String Manipulation in Python appeared first on PythonForBeginners.com.

]]>
We use strings in Python to handle text data. In this article, we will discuss basics of python strings and string manipulation in Python.

What’s a String in Python?

A python string is a list of characters in an order. A character is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash. Strings can also have spaces, tabs, and newline characters. For instance, given below is a string in Python.

myStr="hello world"

Here, we have assigned the string “hello world” to the variable myStr. We can also define an empty string that has 0 characters as shown below.

myStr=""

In python, every string starts with and ends with quotation marks i.e. single quotes ‘ ‘, double quotes ” ” or triple quotes “”” “””.

String Manipulation in Python

String manipulation in python is the act of modifying a string or creating a new string by making changes to existing strings. To manipulate strings, we can use some of Pythons built-in methods.

Create a String in Python

To create a string with given characters, you can assign the characters to a variable after enclosing them in double quotes or single quotes as shown below.

word = "Hello World"
print(word)

Output:

Hello World

In the above example, we created a variable word and assigned the string "Hello World" to the variable. You can observe that the string is printed without the quotation marks when we print it using the print() function.

Access Characters in a String in Python

To access characters of a string, we can use the python indexing operator [ ] i.e. square brackets to access characters in a string as shown below.

word = "Hello World"
print("The word is:",word)
letter=word[0]
print("The letter is:",letter)

Output:

The word is: Hello World
The letter is: H

In the above example, we created a string “Hello World” and assigned it to the variable word. Then, we used the string indexing operator to access the first character of the string and assigned it to the variable letter.

Find Length of a String in Python

To find the length of a string in Python, we can use the len() function. The len() function takes a string as input argument and returns the length of the string as shown below.

word = "Hello World"
print("The string is:",word)
length=len(word)
print("The length of the string is:",length)

Output:

The string is: Hello World
The length of the string is: 11

In the above example, the len() function returns 11 as the length of the string. This is due to the reason that there are 11 characters in the string including the space character.

Find a Character in a String in Python

To find the index of a character in a string, we can use the find() method. The find() method, when invoked on a string, takes the character as its input argument and returns the index of first occurrence of the character as shown below.

word = "Hello World"
print("The string is:",word)
character="W"
print("The character is:",character)
position=word.find(character)
print("The position of the character in the string is:",position)

Output:

The string is: Hello World
The character is: W
The position of the character in the string is: 6

In this example, we searched for the character "W" in the string using the find() method. As "W" is present at index 6 of the string, the find() method gives the value 6 as its output.

If the character is not present in the string, the find() method gives -1 as its output. You can observe this in the following example.

word = "Hello World"
print("The string is:",word)
character="Z"
print("The character is:",character)
position=word.find(character)
print("The position of the character in the string is:",position)

Output:

The string is: Hello World
The character is: Z
The position of the character in the string is: -1

In this example, we passed the character "Z" to the find() method as its input. You can observe that the find() method returns -1 as there is no "Z" in the string "Hello World".

You can also find the index of a character or a substring in a string using the index() method. The index() method, when invoked on a string, takes a character or substring as its input argument. After execution, it returns the index of first occurrence of character or substring as shown below.

word = "Hello World"
print("The string is:",word)
character="W"
print("The character is:",character)
position=word.index(character)
print("The index of the character in the string is:",position)

Output:

The string is: Hello World
The character is: W
The index of the character in the string is: 6

Find Frequency of a Character in a String in Python

You can also perform string manipulation in python to find the frequency of a character in the string. For this, we can use the count() method. The count() method, when invoked on a string, takes a character as its input argument and returns the frequency of the character as shown below.

word = "Hello World"
print("The string is:",word)
character="l"
print("The character is:",character)
position=word.count(character)
print("The frequency of the character in the string is:",position)

Output:

The string is: Hello World
The character is: l
The frequency of the character in the string is: 3

In the above example, we used the count() method find the frequency of the character "l" in the string "Hello World". As there are three instances of "l" in "Hello World", the count() method gives 3 as its output.

Count the Number of Spaces in a String in Python

Spaces are also characters. Hence, you can use the count() method count the number of spaces in a string in Python. For this, you can invoke the count() method on the original string and pass the space character as input to the count() method as shown in the following example.

myStr = "Count, the number of spaces"
print("The string is:",myStr)
character=" "
position=myStr.count(character)
print("The number of spaces in the string is:",position)

Output:

The string is: Count, the number of spaces
The number of spaces in the string is: 4

String Slicing in Python

To perform string manipulation in Python, you can use the syntax string_name[ start_index : end_index ] to get a substring of a string. Here, the slicing operation gives us a substring containing characters from start_index to end_index-1 of the string string_name.

Keep in mind that python, as many other languages, starts to count from 0!!

word = "Hello World"

print word[0] #get one char of the word
print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last character

word = "Hello World"

word[start:end] # items start through end-1
word[start:] # items start through the rest of the list
word[:end] # items from the beginning through end-1
word[:] # a copy of the whole list

To learn how all the statements in the above code work, read this article on string slicing in Python. You can also have a look at this article on string splicing.

Split a String in Python

You can split a string using the split() method to perform string manipulation in Python. The split() method, when invoked on a string, takes a character as its input argument. After execution, it splits the string at the specified character and returns a list of substrings as shown below.

word = "Hello World"
print(word.split(' ')) # Split on whitespace

Output:

['Hello', 'World']

In the above example, we have split the string at the space character. Hence, the split() method returns a list containing two words i.e. 'Hello' and 'World' that are separated by the space character in the original string. You can pass any character to the split() method to split the string.

If the character passed to the split() method isn’t present in the original string, the split() method returns a list containing the original string. You can observe this in the following example.

word = "Hello World"
print(word.split('Z')) # Split on whitespace

Output:

['Hello World']

In the above example, we passed the character "Z" to the split() method. As the character “Z" is absent in the string 'Hello World', we get a list containing the original string.

Check if a String Starts With or Ends With a Character in Python

To check if a string starts with or ends with a specific character in Python, you can use the startswith() or the endswith() method respectively.

  • The startswith() method, when invoked on a string, takes a character as input argument. If the string starts with the given character, it returns True. Otherwise, it returns False.
  • The endswith() method, when invoked on a string, takes a character as input argument. If the string ends with the given character, it returns True. Otherwise, it returns False. You can observe this in the following example.
String Manipulation in Python
String Manipulation in Python

In the above example, you can observe that the string "hello world" starts with the character "h". Hence, when we pass the character "h" to the startswith() method, it returns True. When we pass the character "H" to the startswith() method, it returns False.

In a similar manner, the string "hello world" ends with the character "d". Hence, when we pass the character "d" to the endswith() method, it returns True. When we pass the character "w" to the endswith() method, it returns False.

Repeat Strings Multiple Times in a String in Python

You can repeat a string multiple times using the multiplication operator. When we multiply any given string or character by a positive number N, it is repeated N times. You can observe this in the following example.

Repeat String
Repeat String

In the above example, you can observe that the string "PFB " is repeated 5 times when we multiply it by 5.

Replace Substring in a String in Python

You can replace a substring with another substring using the replace() method in Python. The replace() method, when invoked on a string, takes the substring to replaced as its first input argument and the replacement string as its second input argument. After execution, it replaces the specified substring with the replacement string and returns a modified string.

You can perform string manipulation in Python using the replace() method as shown below.

Replace Substring in a string
Replace Substring in a string

In the above example, you can observe that we have replaced the substring "Hello" from the original string. The replace() method returns a new string with the modified characters.

In the output, you can observe that the original string remains unaffected after executing the replace() method. Hence, you can replace a substring in a string in Python and create a new string. However, the original string remains unchanged.

Changing Upper and Lower Case Strings in Python

You can convert string into uppercase, lowercase, and title case using the upper(), lower(), and title() method.

  • The upper() method, when invoked on a string, changes the string into uppercase and returns the modified string.
  • The lower() method, when invoked on a string, changes the string into lowercase and returns the modified string.
  • The title() method, when invoked on a string, changes the string into titlecase and returns the modified string.
  • You can also capitalize a string or swap the capitalization of the characters in the string using the capitalize() and the swapcase() method.
    • The capitalize() method, when invoked on a string, capitalizes the first character of the string and returns the modified string.
    • The swapcase() method, when invoked on a string, changes the lowercase characters into uppercase and vice versa. After execution, it returns the modified string.

You can observe these use cases in the following example.

String Case Changes
String Case Changes

Reverse a String in Python

To reverse a string in Python, you can use the reversed() function and the join() method.

  • The reversed() function takes a string as its input argument and returns a list containing the characters of the input string in a reverse order.
  • The join() method, when invoked on a separator string, takes a list of characters as its input argument and joins the characters of the list using the separator. After execution, it returns the resultant string.

To reverse a string using the reversed() function and the join() method, we will first create a list of characters in reverse order using the reversed() function. Then we will use an empty string as a separator and invoke the join() method on the empty string with the list of characters as its input argument.

After execution of the join() method, we will get a new reversed string as shown below.

string = "Hello World"
print(''.join(reversed(string)))

Output:

dlroW olleH

In the above example, you can observe that the original string is printed in the reverse order. Instead of the reversed() function and the join() method, you can also use the indexing operator to reverse a string as shown below.

string = "Hello World"
print(string[::-1])

Output:

'dlroW olleH'

Strip a String in Python

Python strings have the strip(), lstrip(), rstrip() methods for removing any character from both ends of a string.

  • The strip() method when invoked on a string, takes a character as its input argument and removes the character from start (left) and end(right) of the string. If the characters to be removed are not specified then white-space characters will be removed.
  • The lstrip() method when invoked on a string, takes a character as its input argument and removes the character from start (left) of the string.
  • The rstrip() method when invoked on a string, takes a character as its input argument and removes the character from the end(right) of the string.

We can strip the * characters from a given string using the methods as shown below.

Strip String in Python
Strip String in Python

In the above example, the original string contains "*" character at its start and end. Hence, we need to pass the "*" character to the strip(), lstrip() or rstrip() method to strip it from the given string.

When we do not pass a character to the strip(), lstrip() or rstrip() method, they take the space character as its value and strips the string on which they are invoked. You can observe this in the following example.

Strip String in Python
Strip String in Python

Concatenate Strings in Python

To concatenate strings in Python, you can use the “+” operator as shown below.

Concatenate Strings
Concatenate Strings

You can concatenate two or more strings using the + operator as shown above.

Check Properties of a String in Python

A string in Python can be tested for Truth value. For this, we can use different methods to check the properties of the string. The return type of these methods is of Boolean type (True or False).

Here is a list of some of the methods to check properties of a string in Python.

word = "Hello World"

word.isalnum() #check if all char are alphanumeric 
word.isalpha() #check if all char in the string are alphabetic
word.isdigit() #test if string contains digits
word.istitle() #test if string contains title words
word.isupper() #test if string contains upper case
word.islower() #test if string contains lower case
word.isspace() #test if string contains spaces
word.endswith('d') #test if string endswith a d
word.startswith('H') #test if string startswith H

Conclusion

In this article, we have discussed different ways to perform string manipulation in Python. To learn more about python programming, you can read this article on list comprehension in Python. You might also like this article on how to build a chatbot in python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

The post String Manipulation in Python appeared first on PythonForBeginners.com.

]]>
https://www.pythonforbeginners.com/basics/string-manipulation-in-python/feed 1 4968
Python String Concatenation and Formatting https://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python Sun, 09 Dec 2012 15:23:37 +0000 https://www.pythonforbeginners.com/?p=1866 One common task you’ll need to accomplish with any language involves merging or combining strings. This process is referred to as string concatenation. This post will describe string concatenation in Python. There are different ways to do that, and we will discuss the most common methods. After, we will explore formatting, and how it works. […]

The post Python String Concatenation and Formatting appeared first on PythonForBeginners.com.

]]>
One common task you’ll need to accomplish with any language involves merging or combining strings. This process is referred to as string concatenation. This post will describe string concatenation in Python. There are different ways to do that, and we will discuss the most common methods. After, we will explore formatting, and how it works.

What is String Concatenation in Python?

When we combine two or more strings in Python, the operation is called string concatenation.

In Python, there are many ways to concatenate or combine two or more strings. When we concatenate two or more strings, the new string is stored in a new string object. Obviously, this is because everything in Python is an object – which is why Python is an objected-oriented language.

In order to merge two strings into a single object, you may use the “+” operator. When writing code, that would look like this:

str1="Python"
str2="ForBeginners"
print("The first string is:",str1)
print("The second string is:",str2)
newStr=str1+str2
print("The concatenated string is:",newStr)

Output:

The first string is: Python
The second string is: ForBeginners
The concatenated string is: PythonForBeginners

In the above code, we have created two string objects str1 and str2. Then, we used the + operator to concatenate both strings. You can also concatenate more than two strings using the + operator as long as all the operands are valid strings. For instance, you can concatenate three strings in Python as shown below.

str1="Python"
str2="For"
str3="Beginners"
print("The first string is:",str1)
print("The second string is:",str2)
print("The third string is:",str3)
newStr=str1+str2+str3
print("The concatenated string is:",newStr)

Output:

The first string is: Python
The second string is: For
The third string is: Beginners
The concatenated string is: PythonForBeginners

Concatenate String and Integer in Python

Python doesn’t support concatenating a string and an integer. These are considered two separate types of objects. If you try to concatenate a string and an integer, the program will run into a Python TypeError exception as shown below.

myStr="PythonForBeginners"
myInt=1117
print("The string is:",myStr)
print("The integer is:",myInt)
newStr=myStr+myInt
print("The concatenated string is:",newStr)

Output:

The string is: PythonForBeginners
The integer is: 1117

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_56401/527270139.py in <module>
      3 print("The string is:",myStr)
      4 print("The integer is:",myInt)
----> 5 newStr=myStr+myInt
      6 print("The concatenated string is:",newStr)

TypeError: can only concatenate str (not "int") to str

In the above output, you can observe that we have tried to concatenate the string “PythonForBeginners” and the integer 1117. Due to this, the program runs into a TypeError exception.

If you still want to merge a string and an integer, you will need to convert the integer to a string. Then, you can perform string concatenation on the two Python strings as shown below.

myStr="PythonForBeginners"
myInt=1117
print("The string is:",myStr)
print("The integer is:",myInt)
newStr=myStr+str(myInt)
print("The concatenated string is:",newStr)

Output:

The string is: PythonForBeginners
The integer is: 1117
The concatenated string is: PythonForBeginners1117

In this example, we first converted the integer 1117 to a string using the str() function. Then, we concatenated the strings using the + operator. Hence, the program executes successfully and we get the output.

Multiply String By a Number in Python

When we multiply a string with an integer N, the string is repeated N times and we get a new string object. You can observe this in the following example.

myStr="PythonForBeginners"
N=3
print("The string is:",myStr)
print("The number is:",N)
newStr=myStr*N
print("The output string is:",newStr)

Output:

The string is: PythonForBeginners
The number is: 3
The output string is: PythonForBeginnersPythonForBeginnersPythonForBeginners

In the above code, we have multiplied the original string by 3. Hence, we get a new string with the original string repeated three times.

If you multiply a string by 0, you will get an empty string as shown below.

myStr="PythonForBeginners"
N=0
print("The string is:",myStr)
print("The number is:",N)
newStr=myStr*N
print("The output string is:",newStr)

Output:

The string is: PythonForBeginners
The number is: 0
The output string is: 

In the above code, we have multiplied the original string with 0. Hence, we get an empty string in the output. Even if you multiply a string with a negative integer, you will get an empty string in the output.

You cannot multiply a string with a floating point number. In this case, the program will run into a TypeError exception as shown in the following example.

myStr="PythonForBeginners"
N=3.5
print("The string is:",myStr)
print("The number is:",N)
newStr=myStr*N
print("The output string is:",newStr)

Output:

The string is: PythonForBeginners
The number is: 3.5

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_56401/1345002117.py in <module>
      3 print("The string is:",myStr)
      4 print("The number is:",N)
----> 5 newStr=myStr*N
      6 print("The output string is:",newStr)

TypeError: can't multiply sequence by non-int of type 'float'

In the above code, we have tried to multiply a string by 3.5. As 3.5 is a floating point number, you can observe that the program runs into a TypeError exception saying that we cannot multiply a sequence by a non-int type of float.

String Concatenation Using The join() Method

If you want to concatenate the strings separated by a string or character as a separator, you can use the join() method. The join() method, when invoked on a separator string, takes a list of strings as its input argument. After execution, it concatenates all the strings in the list by the separator and returns a new string. You can observe this in the following example.

str1="Python"
str2="For"
str3="Beginners"
print("The first string is:",str1)
print("The second string is:",str2)
print("The third string is:",str3)
newStr=" ".join([str1,str2,str3])
print("The concatenated string is:",newStr)

Output:

The first string is: Python
The second string is: For
The third string is: Beginners
The concatenated string is: Python For Beginners

In the above example, we have concatenated three strings using the space character. For this, we invoked the join() method on a string containing the space character and passed a list of all the input strings. After execution of the join() method, we get the desired output.

Suggested reading: String Manipulation

String Formatting in Python

In Python, we can format strings using string interpolation in three different ways.

String interpolation is a term used to describe the process of evaluating a string value that is contained as one or more placeholders. To put it simply, it helps developers with string formatting and concatenation. Hopefully, you are more familiar with the term yourself because it’s a crucial element of any programming language, especially Python.

We can perform string formatting using the following ways.

  • The % operator.
  • Using f-strings
  • The format() method

Let us discuss all three ways one by one.

Formatting Strings Using the % Operator in Python

The % operator uses format specifiers of values as placeholders for string formatting. When invoked on a string, the % operator takes a variable or tuple of variables as input and places the variables in the specified format specifiers in the string. To understand this, consider the following example.

x = "mangoes"
y = 15
z = "The number of %s in the basket is %d." % (x,y)
print(z)

Output:

The number of mangoes in the basket is 15.

In the above example, we have inserted an integer and a string value into the string “The number of %s in the basket is %d.” using the ‘% operator. Here, %s and %d is the format specifier for string and integer respectively. The other format specifiers are %f for float, %c for character, and %e for floating point exponential.

The variables in the tuple on the right side of the % operator contain values that are inserted into the strings. Here, the data type of the values in the variables should be in the same order as the data type defined by the format specifiers. Otherwise, the program will run into error.

x = "mangoes"
y = 15
z = "The number of %s in the basket is %d." % (y,x)
print(z)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_6318/3859633640.py in <module>
      1 x = "mangoes"
      2 y = 15
----> 3 z = "The number of %s in the basket is %d." % (y,x)
      4 print(z)

TypeError: %d format: a real number is required, not str

In the above code, we have passed the integer value as the first element and the string value as the second element in the tuple passed to the % operator. In the string, the first format specifier expects a string and the second format specifier expects an integer. Due to this, the program runs into a TypeError exception.

In the above code, you also need to understand that the values passed in the tuple must be equal to the number of format specifiers in the string. Otherwise, the program will run into an error saying that there are not enough arguments for the format string. You can observe this in the following example.

x = "mangoes"
y = 15
z = "The number of %s in %d baskets is %d." % (x,y)
print(z)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_6318/270842158.py in <module>
      1 x = "mangoes"
      2 y = 15
----> 3 z = "The number of %s in %d baskets is %d." % (x,y)
      4 print(z)

TypeError: not enough arguments for format string

In this example, there are three format specifiers in the string. However, we have passed only two values to the % operator. Hence, the program runs into error.

If we pass more input arguments than the format specifiers in the string, the program again runs into a TypeError exception saying not all arguments are converted during string formatting as shown below.

x = "mangoes"
y = 15
z = "The number of %s in %d baskets is %d." % (x,y,1117,"PFB")
print(z)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_6318/120037793.py in <module>
      1 x = "mangoes"
      2 y = 15
----> 3 z = "The number of %s in %d baskets is %d." % (x,y,1117,"PFB")
      4 print(z)

TypeError: not all arguments converted during string formatting

In this example, there are three format specifiers in the string. However, we passed four values as input to the % operator. Hence, the program runs into error.

Format String Using f-strings in Python

As the name suggests, f-strings are used for formatting strings. In f-strings, you can directly pass the variable name inside curly braces. After execution of the statement, the values in the variable are interpolated in the actual string. You can observe this in the following example.

x = "mangoes"
y = 15
c=1117
z = f"The number of {x} in {y} baskets is {c}."
print(z)

Output:

The number of mangoes in 15 baskets is 1117.

Here, you can observe that we passed the variable names directly to the curly braces in the f-string. Using f-strings has the benefit that you don’t need to care about the order of variables passed to the strings as each variable is passed to the string using its name.

String Formatting Using the format() Method in Python

Instead of the % operator, you can use the format() method for string formatting in Python. In this case, we use curly braces {} instead of the format specifiers for placeholders. When we invoke the format() method on the string containing placeholders, we can pass the values as input arguments to the format() method. After execution of the statement, we get the formatted string. You can observe this in the following example.

x = "mangoes"
y = 15
z = "The number of {} in {} baskets is {}.".format(x,y,1117)
print(z)

Output:

The number of mangoes in 15 baskets is 1117.

While using the format() method for string formatting, if you pass more values to the format() method than the placeholders in the string, the program doesn’t run into an error. However, if you pass fewer values than the placeholders in the string. The program will run into errors.

One benefit of using the format() method is that you do not have to convert integers into a string before concatenating the data. It will do that automatically for you. This is one reason why it is the preferred operator method.

Another useful feature of the format() method is that you don’t actually have to feed the inputs to the interpreter in the same order that you want the variables to be displayed, as long as you specify the indices of the values in the placeholders. For example, you can put the position of the input values in the placeholders and pass the values to the format() method as shown below.

x = "mangoes"
y = 15
z = "The number of {0} in {2} baskets is {1}.".format(x,1117,y)
print(z)

Output:

The number of mangoes in 15 baskets is 1117.

In this output, you can observe that we have numbered the placeholders. Hence, the values are assigned to the placeholders according to the index number and not the actual order of the format specifiers in the string. The value 1117 is still assigned to the third placeholder even after giving it as a second input argument to the format() method. This is due to the reason that the third placeholder contains index 1.

Instead of the indices, you can also name the placeholders and pass the values as key-value pairs to the format() method as shown below.

x = "mangoes"
y = 15
z = "The number of {a} in {b} baskets is {c}.".format(a=x,c=1117,b=y)
print(z)

Output:

The number of mangoes in 15 baskets is 1117.

In this example, we named the placeholders a,b, and c. Then, we assign the values to the names while passing them to the format() method. You can observe that the values are assigned to the placeholders according to their names.

In this article, we discussed string concatenation and formatting in Python. To learn more about Python programming, you can read this article on Python Strings. You might also like this article on Reversing Lists and Strings.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

The post Python String Concatenation and Formatting appeared first on PythonForBeginners.com.

]]>
1866
Python : String Methods https://www.pythonforbeginners.com/basics/python-string-methods Thu, 04 Oct 2012 04:07:16 +0000 https://www.pythonforbeginners.com/?p=1189 String methods are working on the string its called from, if you have a string called, string = “Hello World”, then the string method is called such this: string.string_method() . For a list of string methods, please look at one of my post covering Built In Methods in Strings. Let’s have some fun now and […]

The post Python : String Methods appeared first on PythonForBeginners.com.

]]>
String methods are working on the string its called from, if you have a string called, string = “Hello World”, then the string method is called such this: string.string_method() . For a list of string methods, please look at one of my post covering Built In Methods in Strings.

Let’s have some fun now and show some examples:

string = "Hello World"

print string.isupper()
print string.upper()
print string.islower()
print string.isupper()
print string.capitalize()
print string.split()
print string.split(',')
print string.title()
print string.strip()

If you run that, it should give you an output like this:

False
HELLO WORLD
False
False
Hello world
['Hello', 'World']
['Hello World']
Hello World
Hello World

The post Python : String Methods appeared first on PythonForBeginners.com.

]]>
1189