⚡ Rocket.net – Managed WordPress Hosting

MiltonMarketing.com  Powered by Rocket.net – Managed WordPress Hosting

Bernard Aybouts - Blog - MiltonMarketing.com

Approx. read time: 3.6 min.

Post: Python Basic String Operations

Python Basic String Operations Tutorial

In this tutorial, we will explore the basics of string operations in Python. Strings are sequences of characters enclosed within quotes. Python allows you to perform various operations on strings, such as slicing, indexing, and formatting.

Defining Strings

Strings can be defined using single or double quotes:

astring = "Hello world!"
astring2 = 'Hello world!'
print(astring)
print(astring2)

Explanation

  • astring and astring2 are defined as strings using double and single quotes, respectively.
  • The print function outputs the strings to the console.

You can run the above code using the Trinket.io online Python compiler to see the output.

Printing and String Length

The len() function returns the length of a string, including spaces and punctuation:

astring = "Hello world!"
print("Length of astring:", len(astring))

Explanation

  • len(astring) returns the length of astring, which is 12 characters long.

Indexing and Finding Substrings

The index() method finds the first occurrence of a substring:

astring = "Hello world!"
print("Index of 'o':", astring.index("o"))

Explanation

  • astring.index("o") returns 4 because the first “o” is at index 4.
  • Python uses 0-based indexing, so counting starts from 0.

Counting Occurrences of a Character

The count() method counts the number of occurrences of a substring:

astring = "Hello world!"
print("Count of 'l':", astring.count("l"))

Explanation

  • astring.count("l") returns 3 because “l” appears three times in astring.

Slicing Strings

Slicing allows you to extract parts of a string using the [start:stop:step] syntax:

astring = "Hello world!"
print("Slice astring[3:7]:", astring[3:7])
print("Slice astring[3:7:2]:", astring[3:7:2])

Explanation

  • astring[3:7] returns “lo w”, which includes characters from index 3 to 6.
  • astring[3:7:2] returns “l “, which includes every second character from index 3 to 6.

Reversing a String

You can reverse a string using slicing:

astring = "Hello world!"
print("Reversed string:", astring[::-1])

Explanation

  • astring[::-1] returns “!dlrow olleH”, which is the reversed string.

Converting to Uppercase and Lowercase

The upper() and lower() methods convert strings to uppercase and lowercase, respectively:

astring = "Hello world!"
print("Uppercase:", astring.upper())
print("Lowercase:", astring.lower())

Explanation

  • astring.upper() returns “HELLO WORLD!”.
  • astring.lower() returns “hello world!”.

Checking String Start and End

The startswith() and endswith() methods check if a string starts or ends with a specific substring:

astring = "Hello world!"
print("Starts with 'Hello':", astring.startswith("Hello"))
print("Ends with 'asdfasdfasdf':", astring.endswith("asdfasdfasdf"))

Explanation

  • astring.startswith("Hello") returns True.
  • astring.endswith("asdfasdfasdf") returns False.

Splitting Strings

The split() method splits a string into a list of substrings based on a delimiter:

astring = "Hello world!"
afewwords = astring.split(" ")
print("Splitted list:", afewwords)

Explanation

  • astring.split(" ") splits astring into a list ['Hello', 'world!'].

Exercise: Fix the Code

Try to fix the code to print out the correct information by changing the string s.

s = "Strings are awesome!"
# Length should be 20. above text is 20 characters.
print("Length of s = %d" % len(s))

# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))

# Number of a's should be 2
print("a occurs %d times" % s.count("a"))

# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" % s[1::2]) # (0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end

# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())

# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())

Explanation

  • The len() function calculates the length of the string.
  • The index() method finds the first occurrence of a substring.
  • The count() method counts the occurrences of a substring.
  • Slicing extracts specific parts of the string.
  • The upper() and lower() methods convert the string to uppercase and lowercase, respectively.

You can use the Trinket.io online Python compiler to run and test the above code snippets.

By understanding and practicing these basic string operations, you can manipulate and work with strings effectively in Python.

About the Author: Bernard Aybout (Virii8)

Avatar of Bernard Aybout (Virii8)
I am a dedicated technology enthusiast with over 45 years of life experience, passionate about computers, AI, emerging technologies, and their real-world impact. As the founder of my personal blog, MiltonMarketing.com, I explore how AI, health tech, engineering, finance, and other advanced fields leverage innovation—not as a replacement for human expertise, but as a tool to enhance it. My focus is on bridging the gap between cutting-edge technology and practical applications, ensuring ethical, responsible, and transformative use across industries. MiltonMarketing.com is more than just a tech blog—it's a growing platform for expert insights. We welcome qualified writers and industry professionals from IT, AI, healthcare, engineering, HVAC, automotive, finance, and beyond to contribute their knowledge. If you have expertise to share in how AI and technology shape industries while complementing human skills, join us in driving meaningful conversations about the future of innovation. 🚀