Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

String Programs in Python

Last Updated on September 22, 2023 by Mayank Dham

Strings are the cornerstone of text manipulation and processing in Python. Whether you’re a beginner venturing into the world of programming or an experienced developer aiming to master the intricacies of string handling, a solid understanding of strings is essential. In this article, we embark on a journey to unravel the magic of string program in python, from basic operations to advanced techniques, equipping you with the tools to wield the power of text in your Python programs. A string in Python is denoted by single or double quotations. For example,

# create a string using double quotes
string1 = "Python programming"

# create a string using single quotes
string1 = 'Python programming'

Here, a string variable named string1 has been created. Python Programming is used as the variable’s initial value.

Example of String Program in Python

# create string type variables

name = "Python"
print(name)

message = "I love Python."
print(message)

Output

Python
I love Python.

The name and message variables in the example above contain the values "Python" and "I love Python" respectively.

Although we can also use single quotes, we have used double quotes here to represent strings.

Access String Characters in Python

There are three ways we can get to the characters in a string.

Indexing: One way is to treat strings as a list and use index values. For example,
greet = ‘hello’

# access 1st index element
print(greet[1]) # "e"

Negative Indexing: Python’s strings support negative indexing, just like a list. For example,
g = ‘hello’

# access 4th last element
print(g[-4]) # "e"

Slicing: Access a range of characters in a string by using the slicing operator colon :. For example,
g = ‘Hello’

# access character from 1st index to 3rd index
print(g[1:4])  # "ell"

Note: We will get issues if we try to access an index that is outside of the allowed range or if we use non-integer integers.

Python Strings are immutable

In Python, strings are immutable. That means a string’s characters cannot be modified. For example,

message = 'Hola Amigos'
message[0] = 'H'
print(message)

Output

TypeError: 'str' object does not support item assignment

However, we can assign the variable name to a new string. For example,

message = 'Hola Amigos'

# assign new string to message variable
message = 'Hello Friends'

prints(message); # prints "Hello Friends"

Python Multiline String

A multiline string can also be created in Python. Triple double quotes """ or triple single quotes ”’ are used for this. For example,

# multiline string 
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)

Output

Never gonna give you up
Never gonna let you down

In the above example, anything inside the enclosing triple-quotes is one multiline string.

Python String Operations

Strings are one of the most often used data types in Python because they can be used for a wide variety of operations.

Compare Two Strings

For a string comparison, we employ the == operator. The operator returns True when two strings are equal. Otherwise, it returns False. For example,

str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2
print(str1 == str2)

# compare str1 and str3
print(str1 == str3)

Output

False
True

In the above example,

str1 and str2 are not equal. Hence, the result is False.
str1 and str3 are equal. Hence, the result is True.

Join Two or More Strings

Using the + operator in Python, we can combine (concatenate) two or more strings.

greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

Output

Hello, Jack

In the example above, the + operator was used to combine the strings greet and name.

Iterate Through a Python String

A for loop can be used to iterate through a string. For example,

greet = 'Hello'

# iterating through greet string
for letter in greet:
    print(letter)
greet = 'Hello'

Output

H
e
l
l
o

Python String Length

To determine a string’s length in Python, use the len() function. For example,

greet = 'Hello'

# count length of greet string
print(len(greet))

Output

5

String Membership Test

Using the keyword in, we may determine whether a substring is present within a string or not.

print('a' in 'program') # True
print('at' not in 'battle') False

Methods of Python String

There are other string methods in Python besides those already given. Here are some of those methods:

Methods Description
upper() converts the string to uppercase
lower() converts the string to lowercase
partition() returns a tuple
replace() replaces substring inside
find() returns the index of first occurrence of substring
rstrip() removes trailing characters
split() splits string from left
startswith() checks if string starts with the specified string
isnumeric() checks numeric characters
index() returns index of substring

Escape Sequences in Python

Some characters in a string can be escaped using the escape sequence.

Let’s say we need to include both single and double quotes in a string,

example = "He said, "What's there?""

print(example) # throws error

The compiler will treat "He said, " which contains single or double quotes, as a string. As a result, the code above will result in an error.

To solve this issue, we use the escape character \ in Python.

# escape double quotes
example = "He said, \"What's there?\""

# escape single quotes
example = 'He said, "What\'s there?"'

print(example)

Output

 He said, "What's there?"

The full list of Python-supported escape sequences is provided below.

Escape Sequence Description
\\ Backslash
\’ Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH

Python String Formatting (f-Strings)

Printing values and variables is really simple when using Python f-Strings. For example,

name = 'Cathy'
country = 'UK'

print(f'{name} is from {country}')

Output

Cathy is from UK

Here, f'{name} is from {country}’ is an f-string.

This brand-new formatting syntax is flexible and effective. We will now print strings and variables using f-Strings.

Conclusion
So, with the help of this article, you will have a better understanding of string programs in python. Practice more and more for making good grasp on strings in python.

Other Python Programs
Python program to reverse a number
Python program for heap sort
Python program to check armstrong number
Python program to check leap year
Python program to convert celsius to fahrenheit
Python program to find factorial of a number
Python program to reverse a linked list
Python Program to find the middle of a linked list using only one traversal
Python Program to Add Two Numbers
Python Program to Check Palindrome Number
Python Program to Print the Fibonacci Series
Python Loop Program
Anagram Program in Python
Fizzbuzz Program in Python

Leave a Reply

Your email address will not be published. Required fields are marked *