Python Tutorial – Strings

Python Tutorial - Strings
Reading Time: 6 minutes

This is a continuation of the tutorial series for python programming. Previously I wrote an article in python lists. This article is written in a question-and-answer format. “How to..”, “What is..” themed questions that often appear on the internet. Hence, I’ll answer few questions introducing several strings methods.

1. What is Python Strings?

Strings or Texts are basic components of any data structure. In python, strings are any values that are enclosed in single(”) or double quotes(“”).

# Assigning strings to variables
current_country = "Finland"
native_country = 'Nepal'


#Multi-line comments

personal_info = """ I am Nibesh Khadka. 
I am from Nepal.Currently I live in Finland.
I have degree in IT engineering. 
I am Machine Learning Engineer, Data Scientist, blogger, python developer, Web Developer and many more.
Thanks for reading.



<class 'str'>
<class 'str'>

2. How to multi-line strings without triple quotes?

Use can use a new line escape character ( “\n” ) to change lines and make a multi-line strings.

# Using escape character.
using_esc_char = "This is first line.\nThis is second line."



This is first line. 
This is second line.

3. What is index position? How is it different from counting?

The index is the position of the character in a string. When we count, we usually start from 1. However, the index position starts from 0. Strings can be accessed as: string[index_position]. To clarify, let us try index by normal count.

# Accessing Strings
weather_report="Today's weather is really windy and chilly. I hate it."

#print the length of strings.
print("Length of string is",len(weather_report))

# Lets get last character.
# First lets use length which is 54


Length of string is 54.

Traceback (most recent call last):
  File "", line 42, in <module>
IndexError: string index out of range

Index Error out of range last line indicates that index does not exist that’s because indexing starts from 0, not 1. Hence, the last character index position is:

# Correct way.

# Or using length directly in index



4. How do I slice strings in python? Some examples with variations.

Slicing strings are also a similar step as the list.To slice a string you have to know the length and index info. The basic syntax for slicing is: string_name[start:stop:step]

## Slicing Strings
covid = "Covid-19 pandemic was a biggest tragedy of 2020."

# Slice to get only Covid-19

# Get last 5 characters using -index
print("Last five characters are: ",covid[-5:])

# Get frist 10 characters.
print("Last five characters are: ",covid[:5])

#  Get character 10th to 20th characters.
print("Characters from index 10th to 20th are: ",covid[10:20])


Last five characters are:  2020.
Last five characters are:  Covid
Characters from index 10th to 20th are:  andemic wa

It’s important to remember, that white space is also counted as a string if it’s inside quotes.

5. How to print each character in a string?

Use for loop to loop through strings and print characters.

# For loop and strings.
which_year="This is 2021."
# for loop
for char in which_year:



6. How to print words as a whole in a sentence instead of each character?

String method split() can be used to split the strings and convert them to a list, then use for loop to print each words.

# For loop and split .
which_year="This is 2021."
which_year_list = which_year.split(" ")

# for loop
for word in which_year_list:



7. How to convert a single word to list of characters?

If a single word is passed into list() method it can convert a string to list of character.

# Word to list
vowel_str = "aeiou"

# Print vowel str
print("Vowel letters: ",vowel_str)

# Conversion
vowel_lst = list(vowel_str)

# Print vowel list
print("Vowel letters in a list: ",vowel_lst)


Vowel letters:  aeiou
Vowel letters in a list:  ['a', 'e', 'i', 'o', 'u']

8. How to find the length of a string?

Python’s built-in function len() can be used to find length of strings.

# Find the length of string.
weather_report = "Today's weather is windy in Helsinki."

# print length len()
print("Using len() method: ", len(weather_report))


Using len() method:  37

9. How to check if a certain word/character is in the string?

Python has a keyword “in” that can check the string’s in another string or not. It returns True or False depending on the result. Similarly, “not” together with “in” can be used to check if the search term is not in the string.

# On sentence
sample_1 = "I am a sentence."
#Or in word
sample_2 = "Hi!"

# Using in 
print("Is a is string sample_1?: {}".format("a" in sample_1))

#Using not in
print("! is not in sample_2?: {}".format("!" not in sample_2))


Is a is string sample_1?: True
! is not in sample_2?: False

10. How to use the “if” statement with “in” in strings?

A little tweak in above codes can open more path using if statement.

# Using If with in  and not in
sentence_sample = "I am going to the varsity"

if "am" in sentence_sample:
    print("Given sentence is a present tense.")


I am going to the varsity
Given sentence is a present tense.

Similar logic can be used with “not in” but remember the result of “in” and “not in” means the exact opposite.

11. How to capitalize strings in python or vice-versa?

Python string provides methods “upper()” and “lower” to convert strings to uppercase and lowercase respectively.

# Upper case and Lowercase
# To upper

# To lower
print("THE oCean".lower())


the ocean

12. Can I just make initials uppercase in Python?

Python strings has method “title()” that converts initial in each word to capital letter.

# title
title = "python tutorial - strings"

print("Titles should have initials in uppercase like,:", title.title())


python tutorial - strings
Titles should have initials in uppercase like,: Python Tutorial - Strings

13. How to remove unwanted punctuation from the strings?

String method “strip()” can help remove punctuation from string.

sample_1 = "    'HI !!!!!!!!!!' "
#print the length before stripping
print("Before stripping  length of {} is {}.".format(sample_1, len(sample_1)))

# Remove space's from the edges
sample_1_no_space = sample_1.strip(" ")

#print the length afrer stripping
print("Before stripping  length of {} is {}.".format(
    sample_1, len(sample_1_no_space)))



Before stripping  length of     'HI !!!!!!!!!!'  is 20.
Before stripping  length of     'HI !!!!!!!!!!'  is 15.

13.1 I used strip(“\s+”) but it didn’t work as strip(” “). Why?

It’s true that ” ” or \s+ represent space but \s+ is a regex pattern that is not recognized by the strip method. So, don’t use \s+ for strip methods.

13.2 Can the strip method be used in the middle of the string?

No, strip only handles beginning and end of a string. For anything else you can use replace.

# Repalce
sample_2 = "Hi, I am a programmer."

# Repalce , with !.
print("Before: ", sample_2)

print("After: ", sample_2.replace(",", "!"))


Before:  Hi, I am a programmer.
After:  Hi! I am a programmer.

14. How can I turn a list into a string?

Join can be used to turn list into a string.

# Join 
address =["Helsinki",  "Uusimaa", "00230"]
strengths = ["humor", 'creative', 'positive', 'problem solver']

# Lets join these.
# address with comma and space
address_joined= ", ".join(address)

#print address.
print("I live in {}.".format(address_joined))

#strengths with comma and space and use title() at same time
strengths_joined= ", ".join(strengths).title()

print("My strengths are {}.".format(strengths_joined))


I live in Helsinki, Uusimaa, 00230.
My strengths are Humor, Creative, Positive, Problem Solver.

15. How can we add strings in python?

Adding strings, more precisely string concatenation can be done using different methods.

15.1 Using + to add strings.

# String Concatenation using plus
str_1 = "I am a programmer."
str_2 = "I am also a blogger."

str_concat = str_1+" "+str_2

print("Sentence 1: ", str_1)
print("Sentence 2:",str_2)
print("Combined: ", str_concat)


Sentence 1:  I am a programmer.
Sentence 2: I am also a blogger.
Combined:  I am a programmer. I am also a

15.1.1 What is print (” Sum result: “+ 1), TypeError: can only concatenate str (not “int”) to str ?

When we are using print we often combine two values using “,” or “+”. But what we don’t know is “+” is a strict string operation. It can’t add a non-string to a string. Possible solutions would be

# Either this 
print(" Sum result: ", 1)
print(" Sum result: "+ str(1))

While using comma, remember that it adds extra space without manual addition by coder.

15.2 What is the format() method? How can I use it?

The format is another string concatenation method. Once understood it’s easy and more readable than other methods. Three variations of format:

# String format

# Default mode
# where order matters
age_info = "I am {} years old. I was born in the month of {}".format(
    27, "August")


# Assigning local variable or placeholder
# where order does not make difference but variable name does
relation_status = "I've been {relationship_status} for {years} years.".format(
    years=100, relationship_status="single")


## Formatting integers with palceholders
print("{euro:.1f} euro equivalent in dollars is running for {dollar:.1f} now.".format(euro=1, dollar=1.21 ))


I am 27 years old. I was born in the month of August
I've been single for 100 years.
1.0 euro equivalent in dollars is running for 1.2 now.

16. What is the escape character in python? Give some examples of use cases.

Backslash “\” is also known as an escape character in many programming languages. It’s used to insert supposedly illegal characters in a string. For example:

Error Case:

travel_mode = "I have a car "Hyundai i20"."



travel_mode = "I have a car "Hyundai i20"."
SyntaxError: invalid syntax

We are using double quotes inside double-quotes. But as such what happens is, the first pair double quote ends before car brand and starts after it.

Two methods to work around.

  1. Using escape character right before quotes inside of our main string, no space allowed.
  2. Using single quotes either outside or inside to avoid confusion.
travel_mode_1 = "I have a car \"Hyundai i20\"."
travel_mode_2 = "I have a car 'Hyundai i20'."



I have a car "Hyundai i20".
I have a car 'Hyundai i20'.

Escape character can be used to escape other illegal characters as well.

I hope you like this tutorial blog with a q&a theme. Give it a like and subscribe. You can find the exercise file as a zip down below. If you want more exercise, visit this article: “Python Programming Practice“.

Leave a Reply

%d bloggers like this: