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.

For privacy reasons YouTube needs your permission to be loaded. For more details, please see our Privacy Policy – Legal Disclaimer – Site Content Policy.
For privacy reasons YouTube needs your permission to be loaded. For more details, please see our Privacy Policy – Legal Disclaimer – Site Content Policy.

The Longevity Blueprint: AI-Powered Health Optimization

Current step:1AI-Human Medical Analyzer: Smarter, Personalized Health
2AI-Human Medical Analyzer: Smarter, Personalized Health

> SYS.HEALTH: AI-Human Medical Analyzer_

// Revolutionize Your Diagnostics

Experience the perfect blend of cutting-edge AI precision and expert human care. Our revolutionary analyzer turns your raw health data into personalized, actionable insights tailored just for you.

> INITIALIZING_BIOMETRIC_SCAN...

[+] DATA_INPUT

Securely upload complex health parameters, including lab bloodwork and comprehensive medical history.

[+] PROCESSING

Advanced algorithmic parsing combined with human-level oversight ensures hyper-accurate data interpretation.

[+] OUTPUT_MATRIX

Receive smarter, faster, and truly personalized care strategies to take immediate charge of your health journey.

A name/nickname is required to continue.

> TRANSLATION_MATRIX_ACTIVE...
[ LANG_EN ]
Knowledge Heals, Prevention Protects
[ LANG_HI ]
ज्ञान ठीक करता है, रोकथाम सुरक्षा करती है
[ LANG_ZH ]
知识治愈,预防保护
[ LANG_JA ]
知識は癒し、予防は守る
[ LANG_HE ]
הידע מרפא, המניעה מגנה
[ LANG_AR ]
المعرفة تُشفي، والوقاية تحمي
[ LANG_FR ]
La connaissance guérit, la prévention protège

> SYS.AUTH: Data Processing Consent_

[ AWAITING_AUTHORIZATION ] By providing consent, you allow us to process your uploaded data through our proprietary AI-Human analysis system.

  • [+] SECURE_REVIEW: This ensures your information is carefully reviewed using advanced AI technology and certified professional oversight to deliver personalized health insights.
  • [+] PRIVACY_LOCK: Your privacy is our strict priority. Your data will only be used for this specific diagnostic purpose.

> SYS.UPLOAD: Share Medical Records [OPTIONAL]_

[ USER_CONTROL_ACTIVE ] Uploading your medical records during registration is entirely optional. You can choose to bypass this step and provide data later if it suits your timeline.

You dictate the data flow: share as much or as little as you’re comfortable with, and let us guide you toward better health.

[+] FORMAT_SUPPORT

We accept all file formats, including photos, PDFs, text documents, and raw official medical data.

[+] DATA_YIELD

Increased inputs correlate with higher precision. The more info you share, the better we tailor your personalized insights.

> NEXT_STEPS: Post-Registration Protocol_

Once your registration is complete, a human specialist from our team will personally reach out to you within 3-10 business days. We will discuss your health journey and map out exactly how we can support you.

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. 🚀