Python for Beginners: Strings and Booleans
You will use strings and booleans in almost every Python program. This guide explains how they work.
Strings (Text)
A string is a sequence of characters. You can use letters, numbers, or symbols. Wrap them in single or double quotes.
• Use single quotes: name = 'Ramesh' • Use double quotes: name = "Ramesh" • Use triple quotes for long text: poem = """ Roses are red, Python is great. """
String Operations
You can manipulate text easily with these tools:
- Join strings with +: first + " " + last
- Repeat strings with *: "Ha" * 3 gives HaHaHa
- Find length with len(): len("Python") gives 6
Slicing and Indexing
Python counts positions starting from 0. Use square brackets to grab specific parts of a word.
- word[0] gets the first letter.
- word[-1] gets the last letter.
- word[0:2] gets the first two letters.
Common String Methods
Python has built-in functions to change text:
- text.upper() makes it ALL CAPS.
- text.lower() makes it all lowercase.
- text.strip() removes extra spaces.
- text.replace("old", "new") swaps words.
The Best Way to Format Text
Use f-strings to insert variables into text. It is clean and fast.
example = f"My name is {name} and I am {age} years old."
Booleans (True/False)
Booleans represent logic. A value is either True or False. You use them to make decisions.
Comparison Operators
You get boolean results when you compare values:
- == (Equal to)
- != (Not equal to)
(Greater than)
- < (Less than)
Logical Operators
Combine multiple conditions to build complex logic:
- and: Both sides must be True.
- or: At least one side must be True.
- not: Reverses the result.
Next Steps
Mastering these basics prepares you for control flow and loops. In Part 4, we will learn how to use these tools to make your code take action.
Source: https://dev.to/ramesh_s_a8f0867d239e927c/python-for-beginners-part-3-strings-booleans-6d2
Optional learning community: https://t.me/GyaanSetuAi