Python String

by | Oct 28, 2021 | Python Programming

In this tutorial, we will learn about python string, Manipulating strings in python, and all its functions. Also, we will understand all the string operations which we can perform on python.

Python String

What is a string in Python?

A String is a simple sequence of characters, like a simple text you see here. However, python doesn’t have data type characters like other programming languages.

Assign String to a Variable

Strings in Python can be assigned by either single quotation marks or double quotation marks.

Python String Syntax:

Python strings syntax can be declared using the following method.  Assigning a string to a variable can be done with a variable name followed by an equal sign and a string inside a single quote or in double quotes.

Variable_Name = 'String_Here'

Varibale_Name  = "String_Here"

Variable_Name = str(String / Number )

Let’s check a simple example of string in python.

Example 1:

X = "Python"
Y = 'Google'
print(X)
print(Y)

The output of the above program is:

Python
Google

Let see an example of the Type conversion of string.

X = str(200)

print(X)

print(type(X))

Output:

200
<class 'str'>

Multiline Strings in Python

We can add multiline strings in python using three single quotes just like multiline comments, but unlike comments, we assign it to a variable. 

X = '''Python is a general-purpose interpreted,
        interactive language that supports
        object-oriented programming. It
        is a high-level programming language.
        '''
print(X)

When we run the above program, we will get this result.

Python is a general-purpose interpreted,
        interactive language that supports
        object-oriented programming. It
        is a high-level programming language.

 As we can see, we have printed multiline the same as inside the code with the same format.

Accessing the string as Arrays

As we learn string is nothing but the sequences of characters, we can access individual characters in the string just like we do in arrays in other programming languages. 

What is an array?

Arrays are used to store multiple values in a single variable in programming languages like c,c++, or java, just like we do in a python list. 

We can work on arrays using one of the most popular python libraries called Numpy.

How to access characters in Python String?

The characters or an element can be accessed by square brackets [ ] in python because a single character is a string with a length of 1.

Syntax:

Variable_name = String
String[Index]
String index

Let see an example of how to access a string by index.

Example:

X = "This is an String"

print(X[1])

print(X[4])

print(X[-3])

The output of this program

h

i

Here we can see that based on indexes, we can print the individual characters. One important thing we can see here is a space between h  and I because space is also counted as a character in python, and on the fourth index in our string is a space, so it is printing a space only but in is null, so we cannot see it but the computer can.

Slicing of a String

Slicing of a string in python is a slice or to obtain respective elements from start to end.

Python slicing can be done in two ways.

  • Extending Indexing
  • slice() Constructor

Slicing of a string using extending index

Compared to other programming languages, slicing the string is very easy in Python; unlike C, C++ and java require many lines of code to slice a string in python, it can be done with only one line of code. 

Let’s check the syntax of string slicing.

String[start:end:step]

As we can see, this syntax is the same as we learn in the range function. Well, in the range function, we are using comma(,) in parameters in the string we are using a colon (:) here.

Let see an example here.

String = "I Love Python Programming"

print(String[:3])  # Starting from index zero end at index 3

print(String[2:14]) # Index start at 2 and ends at 7

print(String[-10:-1]) # Index start from negative 2 to negative 7

print(String[2:10:2]) # Here Index is starting at 2 and end at 10 and taking 2 steps in string 

Output: 

I L
Love Python
rogrammin
Lv y

By using some tweaks, we can reverse a string just by changing one thing.

String = "I Love Python Programming"

print(String[::-1])  # Two colons with a start of negative 1 

Output:

gnimmargorP nohtyP evoL I

We can learn about the slice function here.

Merging of Strings

In Python, we can quickly join two or more strings into a single string called the concatenation of two or more strings.

We can merge two strings using the + operation. Just like the addition of two integers, we can add two strings. 

Syntax: 

String3 = String1 + String2

Let understand concatenation with an example.

String1 = "This is First String"

String2 = "This is second String"

String3 = String1 + String2

print(String3)


print("We can add a simple string by adding ", String1 + String2)

When we run this program, we get.

This is First StringThis is second String
We can add a simple string by adding  This is First StringThis is second String

The * operator is used to multiple the string to itself with the given number.

Let’s see a demo using the following program.

String = "Python"

print(String * 4)

Output:

PythonPythonPythonPython

As you can see, String has repeated itself by 4 times.

Using Loop in String

As we have learned that strings are a sequence of characters, we can loop through the characters in a string with a for a loop.

Let’s check an example of a loop in the string.

String = "Python"

for variable in String:
    print(variable)

Output:

P
y
t
h
o
n

Checking String

Python comes with wonderful and powerful features to check whether a particular word or a string is present in a group of sentences.

Here we are using if conditional statement within keyword.

See the example.

String = "We are using Python and we love Python"

if "love" in String:
    print("Word love is present in a string")

See the output:

Word love is present in a string

Let’s see an example with a word not present in a string.

String = "We are using Python and we love Python"

if "Java" in String:
    print("Word 'Java' is present in a string")

The output will be as follows.

 

As you can see, we are not getting any output as word Java is not present in a string, so it’s not returning any result.

The same code can be written in a single line also.

String = "We are using Python and we love Python"

print("Python" in String)

Output:

True

In the same way, we can also use not keyword

String = "We are using Python and we love Python"
print("Python" not in String)

Output:

False

Calculate the length of a String

We can also find the length of a string using python.

Here we are using the len() function, and you can learn more about the len() function here.

Example: 

String1 = "Python"

String2 = "Python is a funny language."

print(len(String1))

print(len(String2))

Output:

6
26

Python Comes with a different set of built-in methods and functions that can be used on strings. All string methods return new values. They do not change the original string.

Method Description
capitalize() Converts the first character to uppercase
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left-justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right-justified version of the string
rpartition() Returns a tuple where the string is part into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, the lower case becomes the upper case and vice versa
title() Converts the first character of each word to uppercase
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

 

 

Was this article helpful?
Share on: