String Manipulation in Python - PythonForBeginners.com (2024)

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

Table of Contents

  1. What’s a String in Python?
  2. String Manipulation in Python
    1. Create a String in Python
    2. Access Characters in a String in Python
    3. Find Length of a String in Python
    4. Find a Character in a String in Python
    5. Find Frequency of a Character in a String in Python
    6. Count the Number of Spaces in a String in Python
  3. String Slicing in Python
  4. Split a String in Python
  5. Check if a String Starts With or Ends With a Character in Python
  6. Repeat Strings Multiple Times in a String in Python
  7. Replace Substring in a String in Python
  8. Changing Upper and Lower Case Strings in Python
  9. Reverse a String in Python
  10. Strip a String in Python
  11. Concatenate Strings in Python
  12. Check Properties of a String in Python
  13. Conclusion

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 WorldThe 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 WorldThe 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 WorldThe character is: WThe 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 WorldThe character is: ZThe 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 WorldThe character is: WThe 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 WorldThe character is: lThe 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 spacesThe 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 wordprint word[0:1] #get one char of the word (same as above)print word[0:3] #get the first three charprint word[:3] #get the first three charprint word[-3:] #get the last three charprint word[3:] #get all but the three first charprint word[:-3] #get all but the three last characterword = "Hello World"word[start:end] # items start through end-1word[start:] # items start through the rest of the listword[:end] # items from the beginning through end-1word[:] # 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 - PythonForBeginners.com (2)

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.

String Manipulation in Python - PythonForBeginners.com (3)

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.

String Manipulation in Python - PythonForBeginners.com (4)

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 Manipulation in Python - PythonForBeginners.com (5)

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.

String Manipulation in Python - PythonForBeginners.com (6)

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.

String Manipulation in Python - PythonForBeginners.com (7)

Concatenate Strings in Python

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

String Manipulation in Python - PythonForBeginners.com (8)

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 alphanumericword.isalpha() #check if all char in the string are alphabeticword.isdigit() #test if string contains digitsword.istitle() #test if string contains title wordsword.isupper() #test if string contains upper caseword.islower() #test if string contains lower caseword.isspace() #test if string contains spacesword.endswith('d') #test if string endswith a dword.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!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

String Manipulation in Python - PythonForBeginners.com (2024)
Top Articles
Latest Posts
Article information

Author: Dean Jakubowski Ret

Last Updated:

Views: 5769

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Dean Jakubowski Ret

Birthday: 1996-05-10

Address: Apt. 425 4346 Santiago Islands, Shariside, AK 38830-1874

Phone: +96313309894162

Job: Legacy Sales Designer

Hobby: Baseball, Wood carving, Candle making, Jigsaw puzzles, Lacemaking, Parkour, Drawing

Introduction: My name is Dean Jakubowski Ret, I am a enthusiastic, friendly, homely, handsome, zealous, brainy, elegant person who loves writing and wants to share my knowledge and understanding with you.