In this Python tutorial you will learn what are Strings in Python programming about various concepts and operations on the Strings supported in Python Programming Language like replacing a character, or reversing a string and various other manipulations.

Python String – Introduction

Python enables us to store a sequence of characters in the form of String and can be defined using single quotes or double quotes. Python Strings are immutable which means that it cannot be changed.

name
 = 'John Doe'
name

‘John Doe’

name = "John Doe"
name

‘John Doe’

Since Python Strings are immutable, so when we apply for instance, a replace method on it, it will create a new copy of the string variable and make changes to it and maintain the original string as it is.

How are strings stored internally in python 3?

Python 3 stores the strings internally as a Unicode Sequence or a sequence of bytes where each character can be of one, two, three, or four bytes depending on the type of Unicode Encoding. Some sample Encodings are: UTF-8, UCS-2, UCS-4 

How to find the number of characters in a Python String?

To find the length of a Python String, we can use the len() method.

It returns an integer value representing the number of characters in the string. We can think of word count in a document as a real-life example of this method.

name "John Doe"
len_var = len (name)
len_var

8

How to access elements in String?

To access elements in a string we can use the concept of indexing. In Python Strings, the count of the elements start from index 0 which means that if we want to access the first element then it will be referred to by ‘0’ and so on.

name = "John Doe"
name[3]

‘n’

We can even use negative index numbers to access the elements from the end of a string.

name = "John Doe"
name[-3]

‘D’

Python Strings also provide us the functionality to slice out a sequence of characters or a sub-string from the given string.

To perform slicing operation we need to follow the following syntax.

String_name[start:end:step]
Where start is the index from which substring starts, the end is the index where slicing stops, and step is an optional argument that determines the increment between each index for slicing.

name = 'John Doe'
name[1:7]

‘ohn Do’

name = 'John Doe'
name[0:7:2]

‘Jh o’

How to reverse a string in python?

To reverse a string in python, we can simply take the advantage of slicing operation by passing the step parameter as -1.

name = "John Doe"
reversedstr = name[::-1]
reversedstr

‘eoD nhoJ’

replace() method in string:

To replace a particular character or a sequence of characters in a string, we can utilize the replace() method.

name = "John Doe"
newname = name.replace('John', 'Jack')
print(name)
print(newname)

John Doe
Jack Doe

upper(), lower() in Python:

If we want to convert all the characters of a string into uppercase or lowercase, Python provides us with the following methods to get the desired output.

name="John Doe"
name.upper()

‘JOHN DOE’

name="John Doe"
name.lower()

‘john doe’

Python String strip() function with Example

Sometimes our string contains some extra whitespace at the start or end of the string. Mostly when a user input is involved, there are many instances when there’s some extra space at the present in the string. We can use strip(), rstrip(), and lstrip() methods to modify our string accordingly.

When we want to remove whitespaces from start as well as end of the string, we use strip() method.

name = " John Doe "
name.strip()

‘John Doe’

To remove whitespace only from end of a string we use rstrip()

name = " John Doe "
name.rstrip()

‘ John Doe’

While removing the whitespace present at the start of the string we can use lstrip() method.

name = "John Doe "
name.rstrip()

‘John Doe ‘

Sorting a Python String:

To sort a string in Python, we use an inbuilt sorted() method.

name = "John Doe"
sorted(name)
[‘ ‘, ‘D’, ‘i’, ‘e’, ‘h’, ‘n’, ‘o’, ‘o’]

Split() method in Python Strings:

To save all the words in a string in the form of a list, we can use the split() method in Python. It takes a separator as an argument, by default its value is whitespace or ‘ ‘.

name = "John Doe"
strlist name.split()
strlist
[‘John’ ‘Doe’]

Splitting using comma as a separator.

var = 'John ate bananas, oranges after lunch'
var.split(',')
[‘John ate bananas’, ‘oranges after lunch’]

Convert Python List into Python String:

We can convert a Python List into a string by using the join() method. The syntax of using join method is as follows:

‘separator’.join(listVariable)

Where separator is the character by which elements of string are to be separated.

strlist = ['John', 'is', 'a', 'good', 'guy']
finalstring = ' '.join(strlist)
finalstring

‘John is a good guy’

In the above code example we have used whitespace as a separator.

Python String Count() with example

If we want to find the number of occurrences of a particular character or a substring, then we can use the count() method.

name = 'John Doe'
name.count('o')

2

Python String find() method with example

To find the starting index of a substring in a given Python String, we can use the find() method, which returns the index from which the substring starts, if the substring is not present then it will return -1. If multiple instances of the substring are present then it will return the index of first occurrence of substring.

name = 'John Doe'
name.find('Do')

5

name = 'John Doe'
name.find('o')

1

We frequently see the application of this method in finding whether a particular word is present in the document or webpage or not.

Python String format() with examples

The format() method in Python Strings enables us to insert the value(s) inside a string’s placeholder.

'The {} is situated at {} Bakers Street'.format("house',49)

‘The house is situated at 49 Bakers Street’

We can even assign names to the placeholders and insert their values accordingly.

'The {name} is situated at number} Bakers Street'.format(number - 49, name - "house)

‘The house is situated at 49 Bakers Street’

Convert Integer or float value into a Python String:

In Python Programming, to convert a numeric value i.e. integer or float into a string value, we can use the str() method.

Converting an integer to string value.

num = 92
str(num)

’92’

Converting a float value to a string

float_num = 12.1
str(float_num)

‘12.1’

How to find the length of a list in Python?

To find the length of a list, we use len() method.

mylist = [1,2,3]
len(mylist)

3

How to find the length of a dictionary in Python?

To find the length of a dictionary, we will again use len() method.

mydict = {'a':1,'b':2, 'c':3}
len(mydict)

3

How to find the length of a tuple in Python?

Since a tuple is also an iterable object like a list in Python therefore we can use len() method to find out its length.

mytuple = (1,2,3)
len(mytuple)

3

Explore Goals at TechLearn –

Choose your Goal at TechLearn - Python programmer

Live sessions in various Goals –

You can also get the complete python tutorial at their official website – The Python Tutorial — Python 3.9.4 documentation

LEAVE A REPLY

Please enter your comment!
Please enter your name here