Python Strings

Strings in Python is like a text that may contain an alphabet, numerical value, space as well as special characters. The only condition is: those characters should be enclosed by a single or double quote.

This is a comprehensive python strings guide. All the syntax, functions, methods related with strings are mentioned here.

Creating String in Python

We can create strings in python using single or double-quotes. Below is the example code:

# Python string example using single quote.
str1 = 'Hello World!'    # Sentence in a string
str2 = 'Hello'           # Single Word 
str3 = 'Hello123'        # Alphabet with numbers
str4 = '123'             # Numbers
str5 = ''                # Empty String
str6 = ' '               # space only
str7 = '^&#'             # special characters only
# Python string example using double quote.
str1 = "Hello World!"    # Sentence in a string
str2 = "Hello"           # Single Word 
str3 = "Hello123"        # Alphabet with numbers
str4 = "123"             # Numbers
str5 = ""                # Empty String
str6 = " "               # space only
str7 = "^&#"             # special characters only

Creating multiple lines string

We can create multiple-line strings using a triple quote. This is useful when you have to create a text that contains many lines.

# Python multiline string using triple quote
mult_str = '''Let's create a multiline string.
           We can use triple quotes to do that.'''
print(mult_str)

Output:

Let's create a multiline string.
We can use triple quotes to do that.
# Python multiline string using triple quote
mult_str = '''Let's create a multiline string.
           We can use triple quotes to do that.'''
print(mult_str)
Let's create a multiline string.
We can use triple quotes to do that.

String Concatenation

We can concatenate (combine) two strings using the ‘+’ operator.

# string concatenation example
str1 = "Hello"
str2 = "World!"
print(str1 + str2)

Output:

HelloWorld!

You can see there is no space between the two words. To correct that, we can do:

# string concatenation example
str1 = "Hello"
str2 = "World!"
print(str1 + ' ' + str2)

Output:

Hello World!

The same thing can be done by giving space after the first word or before the second word.

# string concatenation example
str1 = "Hello "
str2 = "World!"
print(str1 + str2)

Output:

Hello World!

Escape characters in string

Escape characters give different interpretations of the same thing. In python, we use backslash \ followed by the escape character.

Suppose we have to create a text that itself contains a single quote. for eg. That’s a cow.

If we try without the syntax of the escape character, we get errors.

str_ex = 'That's a cow.'   # single quote in a string
print(str_ex)

Output:

str_ex = 'That's a cow.'   # single quote in a string
                   ^
SyntaxError: invalid syntax

This can be solved using the syntax of the escape characters.

str_ex = 'That\'s a cow.'   # single quote in a string
print(str_ex)

Output:

That's a cow.

There are many escape characters in strings that are used for different purposes. Some of them are:

  • \n for new line
  • \’ for single quote
  • \” for double quote
  • \\ for backslash
  • \t for tab (default is 4 space)
  • \b for backspace(to remove previous character)

Let’s see the example code of the above escape characters.

# Escape characters in python
ex1 = 'He is a boy.\nAnd he loves to play.'
ex2 = 'He says,\'I love to play.\''
ex3 = "He says,\"I love to play.\""
ex4 = 'In latex, the syntax is \\begin{document}'
ex5 = 'This is \t a tab.'
ex6 = 'Let us playy\b football.'
print(ex1)
print(ex2)
print(ex3)
print(ex4)
print(ex5)
print(ex6)

Output:

He is a boy.
And he loves to play.
He says,'I love to play.'
He says,"I love to play."
In latex, the syntax is \begin{document}
This is          a tab.
Let us play football.

String slicing in python

We can extract a specific letter(character) or a group of letters(characters) from a string using the slicing method. This method works in python lists also.

Every character in a string is indexed with values (both positive and negative).

python string indexing
indexing in python string

We can use the syntax string[index] to get the character of that index from a string.

Let’s use positive index:

# Getting character using +ve index
str = "Hello World!"
print(str[0])
print(str[4])
print(str[9])
print(str[11])

Output:

H
o
l
!

Now let’s use negative index

# Getting character using -ve index
str = "Hello World!"
print(str[-12])
print(str[-8])
print(str[-3])
print(str[-1])

Output:

H
o
l
!

We can also extract characters from one index to another index using a syntax:

Syntax: string[start : stop : step]

Let’s first use the syntax without step value. start is the index from which you want to start extracting characters and stop is the index where extracting stops, not including the stop index.

Slicing can be done both with positive and negative indexes. REMEMBER: Do not mix both positive and negative indexes while slicing.

Using Positive index in slicing:

# Slicing strings in python
# using positive index
str = "Hello World!"
print(str[2:5])     # index 5 is not included
print(str[1:7])     # index 6 is not included
print(str[5:10])    # index 10 is not included

Output:

llo
ello W
 Worl

Using negative index in slicing.

# Slicing strings in python
# using negative index
str = "Hello World!"
print(str[-7:-1])     # index -11 is not included
print(str[-10:-3])     # index -3 is not included

Output:

 World
llo Wor

If start index is not given, slicing starts from the first letter, and if stop index is not given, slicing ends on the last letter.

# Slicing strings in python
str = "Hello World!"
print(str[:8])     # index 0 to index 7 (index 8 not included)
print(str[8:])     # index 8 to last
print([:])         # full string

Output:

Hello Wo
rld!
Hello World!

From the above example, we can say: str[:8] + str[8:] = str. Hence

str[:i] + str[i:] = str, where i is any index between the first character and last character index.

Now, Let’s use step value also for slicing.

# Slicing strings in python
str = "Hello World!"
print(str[1:6:2])     # index 1 to index 5 with the steps of 2
print(str[:10:3])     # index 0 to index 10 with steps of 3
print([4::2])         # index 4 to last with steps of 2

Output:

el 
HlWl
oWrd

Remember: positive step value makes slicing from left to right direction whereas negative step value makes slicing from right to left direction.

Let’s see an example code with a negative step value. While using the negative step value, the start should be chosen from the right side, and the stop should be from the left side.

# negative step makes 
# slicing from right to left
str = "Hello World!"
print(str[::-1])       # string in reverse order
print(str[::-2])       # string in reverse with 2 step value.
print(str[10:2:-1])    # string om reverse from index 10 to index 3
print(str[-5:-10:-1])  # string on reverse from index -5 to -9      

Output:

!dlroW olleH
!lo le
dlroW ol
oW ol

len() internal function on string

We can find the number of characters in a string using an internal function len(). Then syntax is len(string)

# using len() function on string
str = "Hey! I really like python"
print(len(str)) 
print("The length of str : ", len(str)) 

Output:

25
The length of str :  25

Looping through a string

String in a python is iterable. That means, we can iterate through the string. There are many ways to iterate through a string.

for loop in a string

# for loop in a string
string_eg = "I love Python"
for char in string_eg:
    print(char)

Output:

I

L
o
v
e

P
y
t
h
o
n

We can do the same loop using a range() function.

# for loop in a string
string_eg = "I love Python"
for index in range(len(string_eg)):
    print(string_eg[index])

Output:

I

L
o
v
e

P
y
t
h
o
n

zip() function in strings

zip() function is used to combine many strings so that they can be iterate together. Remember: If the length of strings to be combined are not equal, the zip() function iterates with the length of the short string.

# zip(string1, string2, ...) example code
str1 = "Python"
str2 = "Love
str3 = 'Language'
for i, j, k in zip(str1, str2, str3):
	print(i, j, k)

Output:

P L L
y o a
t v n
h e g

enumerate() functions in strings

Enumerate function can be used to get the index of the characters in a string along with that character.

# enumerate(string) example code
str_eg = "I love Python"
for i, j in enumerate(str_eg):
	print(i, j)

Output:

0 I
1  
2 l
3 o
4 v
5 e
6  
7 P
8 y
9 t
10 h
11 o
12 n

Check the presence of character(s) in a string

We can check the presence of character or characters in a string using a in and not in keyword.

The syntax is: character in string

If the specified character is present in the string, it returns True and if not present, it returns False.

# use of in keyword
str1 = "I love Python"
print('y' in str1)
print('love' in str1)
print('yth' in str1)
print('to' in str1)

Output:

True
True
True
False
# use of in keyword
str1 = "I love Python"
print('y' in str1)
print('love' in str1)
print('yth' in str1)
print('to' in str1)
True
True
True
False

The syntax is: character not in string

If the character is not in string, it returns True and if it is present, it returns False.

# use of in keyword
str1 = "I love Python"
print('c' not in str1)
print('love' not in str1)
print('yth' not in str1)
print('to' not in str1)

Output:

True
False
False
True
# use of in keyword
str1 = "I love Python"
print('c' not in str1)
print('love' not in str1)
print('yth' not in str1)
print('to' not in str1)
True
False
False
True

Sharing is Caring

Leave a Comment

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