Home » Python Tutorial » Python String

Python String


Reading Time - 13 mins

One of the most commonly used data types in python is strings. A Python String is an array of bytes representing Unicode characters. Since there is no such data type called character data type in python, we can say, a single character is a string of length 1. In this detailed tutorial, we will tell you about the Python String.

String literals in python are always surrounded by either single/double quotes. ‘hello’ and “hello” are the same.

print('hello world')
print("hello world")

We will get an error if there is a quotation mismatch.

print('hello world")
print("hello world')

Python String Variable

We can assign a string to a variable by, giving the variable name followed by an equal sign and a string.

var='Hello World!'
print(var)

Common Python String Operations

There are following string operations for python string.

Access String

In Python, we can access individual characters of a String using their index. The index always starts with 0 i.e. index 0 refers to the first character, 1 refers to the second character, and so on.

a='Hello'

Access Characters of String

To print each character, try the below code. If a string is of length ‘l’ then the index of the last character will be ‘l-1′(since the index starts with 0).

print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[4])

Accessing an index out of the range will cause an IndexError. The below code will throw the index error because the variable ‘a’ is of length 5 so the index of the last character will be 4.

print(a[5])

The index can only be an integer data type. We will get TypeError if we use any other data types.

print(a['a'])

String Slicing

Slicing is used to return a range of characters within a string. We can get a part of the string, mention the start index and the end index, separated by a colon. To print characters starting from index 2 to index 4, try the below code

print(a[2:5])

To print until the 4th character, the end index has to be 5(index 5 will not be included). If a string is of length ‘l’ and to slice the whole string, the code is

print(a[0:l])

The end index is an optional one. If you are not giving the end index, by default it will print till the end of the string.

print(a[0:])

Negative Indexing

Negative indexes are used to slice from the end of the string. In negative indexing, the last character will be of index -1, character before the last character will be -2, and so on. Considering the string of length l, the first character will be of length -l.

print(a[-5:-1])

To print the whole string using negative index

print(a[-5:])

Conclusion

Python String

In the above image, it is shown how the positive and negative indexing has been used access to the characters in a string. Please try out more examples of slicing to get familiar with it. Next, we will cover the built-in methods used for string operations.

READ  Python Exception

In the last tutorial, we have seen how to slice a string using both positive and negative indexes. In this session, let’s see the basic builtin methods we use on strings.

Built-in String Methods in Python

I am using this variable ‘a’ for all the examples

a="Hello, World!"

len()

len() method is used to get the length of a string.

len(a)

lower()

The method lower() returns the string in lower case

a.lower()

upper()

The upper() method returns the string in upper case

a.upper()

split()

The split() method splits the string into a list of substring when it finds instances of separators. In our example the separator is ‘,’. Don’t worry about the list, we have a separate topic on that in the upcoming tutorials.

a.split()

strip()

strip() removes the leading and trailing white spaces in the string
lstrip() removes leading white spaces alone and
rstrip() removes the trailing white spaces

b='    Hello, world!     '
b.strip()
b.lstrip()
b.rstrip()

replace()

replace() method replaces the substring of a string with another substring.

a.replace('World',"Jude")

If you print the variable ‘a’, it will still print “Hello, World!”. The reason being, strings in python are immutable, meaning you can never change the string. If you want the replaced value of a string, just assign it to another variable.

b=a.replace('World',"Jude")
print(b)
print(a)

String Concatenation in Python

‘+’ is used to combine 2 strings

x='Hello'
y='World'
z=x+' '+y

find()

find() – Searches the string for a specified value and returns the position of where it was found. If more than once occurrences are found, it returns the index of the first occurrence

a.find('l')

capitalize()

Converts the first character of a string to Upper Case.

'hello world'.capitalize()

isalpha()

Returns True if all characters in the string are in the alphabet. The below code will return False because ‘a’ contains special characters ‘,’ and ‘!’

a.isalpha()

isdigit()

Returns True if all characters in the string are digits.

a.isdigit()

Conclusion

I have covered the most commonly used built-in methods. Please try out more examples. Next, I will cover some of the advanced string operations and then proceed with other built-in data types.

READ  Default Arguments and Positional arguments in Python

Reverse String in Python

Let’s go back and see whats the syntax we used for string slicing

string[start index: stop index]

To be more accurate, the correct syntax to slice a string is

string[start index: stop index: step]

start index- where to start the slicing
stop index- index till which we need to slice
step- in how many strides(by default, this will be 1

Let us see an example to understand how the step parameter works:

a='hello world'
l=len(a)
helloworld
12345678910

a[0:l:1] – will print all the characters in a string
a[0:l:2] – will start at index ‘0’, goes till the end but with a step ‘2’. Means, it starts from 0, then takes 2 steps, prints the character at index ‘2’. Takes 2 steps, prints the character at index 4, then 6, and so on.
The step can be given in negative as well. Try out more examples.

Let’s come to the actual topic, how to reverse a string using the above concept. Take time to work it out. If you are not sure, try the below code:

a[::1]
a[::-1]

a[::1] – prints the entire string.
a[::-1]- prints the entire string in reverse. Since the step is negative, it means to start at the end of the string and end at position 0, move with the step -1, the negative one, which means one step backward.

String Format in Python

Try the below code:

bmi=18
print("The bmi of person A is "+bmi)

The above code will throw an error because we are trying to concatenate a string and an integer.

With format() we can achieve that. The syntax is

print("The bmi of person A is {}".format(bmi))

format() accepts multiple arguments as well:

bmi=18.5
status='normal'
print("The bmi of person A is {} and he is {}".format(bmi,status))

You can also assign arguments to variables, like this:

print("The bmi of person A is {a} and he is {b}".format(b=status,a=bmi))

Conclusion

With this, the strings are over. In the next tutorial, we will cover the other inbuilt data types.

READ  Python Loops

Reference

Reference 1

Install Python

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions