Python String – A Comprehensive Tutorial with Examples

Updated on September 14, 2024

Article Outline

In Python, String is used for storing the URL(Uniform Resource Locator), file paths, JSON data, and virtually any textual information. Python strings are sequences of individual characters, which means we can access the specific characters of a string using indexing and slicing.

 

Syntax of Python String

str=” My Name is Python” print(str)
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

What is a String in Python?

In the Python programming language, a string is a sequence of characters within either single quotes, double quotes, or triplet quotes. Strings can contain letters, numbers, symbols, and whitespace characters. Python strings are immutable, which means the content of the string cannot be changed once it is defined.

Creating a Python String

In the Python programming language, we make the strings by enclosing them in single or double quotation marks. Python programming language also supports the triple quotes for defining the Python programming language.

 

Python String Example

 

str='Hello Python Programming language' print(str) str2 = "Hello Python 2" print(str2) str3 = “”" Hello Python 3"”” print(str3)

Python String Indexes

In the Python programming language, we also can access individual characters from the string using the indexes. Each character in a string has a unique index. It starts from 0 for the first character, 1 for the second character, and so on. In the Python programming language, we can also access the string using the negative indexes. We can access the end of the string, with -1 representing the last character, -2 representing the second to last character, and so far.

 

Python Program

 

str="Programming" print("Positive Indexing") print(str[0]) print(str[1]) print(str[2]) # negative indexing print("Negative Indexing") print(str[-1]) print(str[-2]) print(str[-3])

 

Output

 

Positive Indexing P r o Negative Indexing g n I

Accessing Characters in Python String

In Python, we can access the string using indexing. Indexing allows negative and positive characters from the back of the string. For example, -1 refers to the last character of the string, -2 refers to the second-last character in the string, and so on.

 

Accessing the index out of the range will cause an IndexError in Python language.

 

Program

 

str = "herovired" print(str[0])

 

Output

h

Strings Indexing and Splitting

String Indexing: In Python, a string is a sequence of characters. Using Python’s indexing, we can get the individual character by the single character. The index starts from 0, the second index is 1, and so on.

 

The following program demonstrates the example

 

Program

 

str = "Hello" print(str[0]) print(str[1]) print(str[2]) print(str[3]) print(str[4])

 

Output

H e l l o

 

Splitting: We can split the string using the split() function in Python. This method splits a string into a list using a specified delimiter. The following program demonstrates the string splits().

 

Program

 

string = "one, two, three" words = string.split(',') print(words)

 

Output

 

['one', 'two', 'three']

Reversing a Python String

In the Python programming language, we also reverse a string using the string slice method. In this example, we will reverse a string by accessing the index. In slicing, we will not specify the first two parts of the slice. That indicates that we are considering the whole string, from the last point to the last index.

 

The following program demonstrates the reverse of a string.

 

Program

 

#Program to reverse a string

str2 = "helloworld" print(str2[::-1])

 

Output

dlrowolleh

Deleting Strings in Python

String are immutable characters. In the simple world. After assigning the string, we cannot make any changes to it. We cannot make any changes to it. We cannot remove or delete any character of the string. But in Python, we can delete the whole string using the del keyword.

 

The following program demonstrates the model keyword in Python

 

Program

 

str = "Helloworld" print(str) del str ; print(str)

 

Output

 

Helloworld <class 'str'>

Updating/Reassigning Strings in Python

Strings are immutable. It means, we cannot change the string after the declaration. But we can reassess the string in Python. Stings cannot be completed with a new string. Let’s see the following example of string reassigning.

 

Program

 

message="Welcome to the Programming world" print(message) message="Hacking World" #reassigning a new string print(message)

 

Output

 

Welcome to the Programming world Hacking World

Python Escape Sequence

A character with a backslash () just before it is called an escape sequence or escape character. We use escape characters to perform specific tasks while running your program. Escape Sequence is used when a programmer wants to add double quotes or single quotes in a program. There are many escape sequence characters available in the Python language.

 

List of Escape Sequences Available in Python

  

Escape Sequence Meaning
Single Quote
Double Quote
Backslash
n Newline
r Carriage Return
t Horizontal Tab
b Backspace
f Formfeed
v Vertical Tab
0 Null Character
N{Name} Unicode character named in database lookup
uxxxxxxxx Unicode character with a 16-bit hex value
Uxxxxxxxx A Unicode character with a 32-bit hex value
000 A character with octal value ooo
xhh The character with a hex value

 

Also Read: Arrays in Python

Python String Formatting

In Python, we can format the string data type with the use format() method, which is a versatile function for formatting strings in Python. The format method contains curly braces {} as a placeholder, which can hold the arguments according to the position or keyword to specify the order.

 

Example: In this example, we will declare a string containing curly brackets and pass the dynamic string in these curly braces.

 

Program

 

# Python Program for # Formatting of Strings # Default order String1 = "{} {} {}".format('Hello', 'Programming', 'World') print("Print String in default order: ") print(String1) # Positional Formatting String1 = "{1} {0} {2}".format('Hello ', 'Programming', 'World') print("nPrint String in Positional order: ") print(String1) # Keyword Formatting String1 = "{l} {f} {g}".format(g='Hello', f='Computer', l='Programming') print("nPrint String in order of Keywords: ") print(String1)

 

Output

 

Print String in default order: Hello Programming World Print String in Positional order: Programming Hello  World Print String in order of Keywords: Programming Computer Hello

Iterate a String using a loop

We can also iterate the string using the while loop and for loop in Python language. Python allows access to the single characters in the string one by one using any loop.

 

Using a for-loop: The following program demonstrates the for-loop example in Python

 

str = "hello world" for c in str: print(c)

 

Output

h e l l o w o r l d

Using a while loop: The following program iterates a String using a while loop.

 

string = "Hello World" index = 0 while index < len(string): print(string[index]) index += 1

 

Output

 

H e l l o W o r l d

Useful Python String Operations

Python language provides various operations to manipulate strings efficiently. Here I am discussing the common operations that are performed in strings.

  • Logical Operators on String
  • String Template Class
  • Split a string
  • String Slicing
  • Find all duplicate characters in string
  • String formatting using %

Python String Constants

 

Built-in Function Description
string.ascii_letter Concatenation of the ascii_lowercaes and ascii_uppercae constants
string.ascii_lowercase Concatenations of lowercase letters
string.ascii_uppercase Concatenations of uppercase letters
string.digits Digit in strings
string.letters Concatenation of strings lowercase and uppercase
string.lowercase A string must contain lowercase letters
string.octdigits Octadigit in a string
string.punctuation ASCII characters have punctuation characters.
string.printable Strings of characters which are printable
Strig.endswith() Return true if the string ends with a given suffix otherwise, this method returns false.
Strings.startswith() This method returns true if a string starts with the given prefix otherwise. This method
returns false.
String.isdigit() This method returns true if all characters are digits otherwise. This method returns false.
String.isdecimal() This method returns true if all characters are decimal
str.format() This method allows substitution in an existing string
String.index This method returns the position of the first occurrence of a substring in a string
replace() This method returns the string where all strings are replaced with another string.
string.swapcase() This method converts all uppercase characters to lowercase and vice versa of the given
string.

 

Compare Strings in Python

We can compare the string in Python using the comparison operators (==,!=,<,> <=, >=) compare strings.

 

The following program demonstrates the comparison of the strings.

 

Program

 

string1  =  "apple" string2  =  "Apple" print(string1  ==  string2) print(string1  !=  string2) print(string1  <  string2) print(string1  >  string2) print(string1  <=  string2) print(string1  >=  string2)

Output

False True False True False True

String Membership Test

The string member is nothing much. It is the test to check if a substring is present in a certain string.

 

To check if a substring is present in a string, we can use the “in” operator. The result of this statement would be a boolean value. It will return true if the substring is present in the string; otherwise, it will return false.

 

Program

 

print('str' in 'str is present or not str') print('word' in 'Harry Potter')

 

Output

 

True False

Unicode String

In Python language, normal strings are stored internally as 8-bit ASCII, while Unicode strings are stored in 16-bit Unicode. Unicode strings allow you to work with different language and character sets.

 

The following program demonstrates the Unicode String example.

 

Program

 

# Creating a Unicode string directly unicode_str = "Hello, 世界!" print(unicode_str)

 

Output

 

Hello, 世界!

Multi-line Strings

We can also implement multi-line strings in the Python language. To do so, we use backlash, brackets, and triple quotes.

 

The following program demonstrates a multi string example in Python

 

Program

 

multiline_string = '''This is a multiline string.''' print(multiline_string) colors = ("multi-line string" "red n" "blue n" "green n" "yellow n" ) print(colors) x = "multiline String" "I love Python" "Python Language" print(x)

 

Output

This is a multiline string. multi-line string red blue green yellow

Python String Methods

Python programming language offers a rich set of string methods that allow developers to manipulate and process text efficiently. These methods are essential for Python programmers. A string is a fundamental data type in the Python language. It is used in a wide range of applications. Below are some useful string methods, along with practical examples to demonstrate their usage.

 

  • upper(): This string method is used to convert a string into Uppercase
  • lower(): This string method is used to convert a string into lowercase
  • split(): This method divides a string into a list of substrings based on a delimiter
  • join(): This method joins the elements of an iterable into a single string, using the string as a delimiter.
  • find(): This method finds the first occurrence of the specified string otherwise, it will return the -1 if the value is not found.
  • count(): This method returns the number of characters that occur in the string
  • replace(): This method replaces a specified string with another specified string.

Program

 

text = "Hello, World!" print(text.upper())  # Output: HELLO, WORLD! print(text.lower())  # Output: hello, world! text = "   Hello, World!   " print(text.strip())  # Output: Hello, World! text = "   Hello, World!   " print(text.strip())  # Output: Hello, World! text = "Python is versatile and powerful" words = text.split() print(words)  # Output: ['Python', 'is', 'versatile', 'and', 'powerful'] new_text = '-'.join(words) print(new_text)  # Output: Python-is-versatile-and-powerful text = "Python is powerful, and Python is easy to learn." print(text.find("Python"))  # Output: 0 print(text.count("Python"))  # Output: 2 text = "Python is easy to learn" new_text = text.replace("easy", "fun") print(new_text)  # Output: Python is fun to learn

 

Output

 

HELLO, WORLD! hello, world! Hello, World! Hello, World! ['Python', 'is', 'versatile', 'and', 'powerful'] Python-is-versatile-and-powerful 0 2 Python is fun to learn

List of String Methods in Python

Python has a rich set of string methods. Here is the list of in-built Python string methods.

 

Methods Descriptions
center() This method aligns the string in the center
count() This method counts the string characters
encode() This method encodes the string,  using the specified encoding.
endsWith() This method returns true if the string ends with a specified value; otherwise returns false.
expandtabs() This method sets the tab size to the specified number
find() This method finds the first occurrence of the string if the string is not found, it will
return -1
strip() This method removes any leading and trailing whitespaces.
format_map() This method returns a dictionary value.
index() This method finds the first occurrence of species value
isalnum() This method returns true if the string is alphanumeric otherwise, It will return false.
isalpha() This method returns true if all the characters are alphabet
isdecimal() This method returns true if all the characters are decimal; otherwise, it will return false
isdigit() This method returns true if all the characters are digits otherwise, it will return false.
isidentifier() This method returns true if the string is a valid identifier otherwise, it returns false.
islower() This method returns true if all the characters are lower otherwise, it will return false.
isnumeric() This method returns true if all the characters are numeric otherwise, It will return false.
isprintable() This method returns true if all the characters are printable otherwise, it will return
false.
lower() This method returns a string where all the characters are lower
lstrip() This method removes any leading characters from the strip
maketrans() This method returns a mapping table
partition() This method searches the specified string in the string.
replace() This method replaces a specified string with a specified string.
isprintable() This method returns true if all the characters in the string are printable. If not, it
returns false.
istitle() This method returns true if all words are strings are titles otherwise returns false
rfind() This method returns the highest index of the substring
splitlines() This method splits the lines at line boundaries
zfill() This method adds zeros(0) at the beginning of the string until it reaches the specified
length of the string.
rpartition() This method splits the string into three parts

 

Also read: Pandas in Python

Conclusion

In this article, we learned about various types of string methods in the Python programming language. We learned about the reverse() method for reversing the string and the replace() method for replacing the specified string with a specific string. Python provides a rich set of built-in methods for string manipulations, allowing you to perform various operations efficiently. If you want to learn more about the Python programming language, you can check out the Accelerator Program in Business Analytics and Data Science.

FAQs
Python string methods are built-in methods in Python that operate on strings. These allow you to perform various kinds of operations on strings, like manipulation, searching, formatting, replacement, etc.
In the Python programming language, we can use the upper() case method, which converts a string into uppercase.
The startswith() method checks whether a string starts with a particular substring.
The list() method converts a string to a list of characters, and we can use the ‘join()’ method to concatenate a list of characters into a single string.
We can use the ‘find()’ method to find the index of the first occurrence of a substring within a string. If the substring is not found, It will return ‘-1’.

Updated on September 14, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved