π§΅ Python Part 2: Strings and User Input in Python
1οΈβ£ What is a String?
Creating strings with single or double quotes
Python treats all input from
input()as strings
2οΈβ£ Python String Formatting Methods
%Formatting (C-style)- Format specifiers:
%s,%d,%f
- Format specifiers:
.format()method- Positional placeholders
f-strings(Modern and recommended)β Summary Table: Python String Formatting Styles
3οΈβ£ String Concatenation in Python
Definition and basic example
Mixing strings with other data types
Comma
,vs plus+in printAccidental line breaks and multiline concatenation
Alternatives:
f-strings,.format()π Summary Table: Concatenation Methods
4οΈβ£ String Repetition in Python
What is repetition (
*)Pitfalls to avoid (
TypeError)Print tricks with
\nand emojis
5οΈβ£ Measuring String Length with len()
What is
len()Examples with letters, spaces, emojis
Real-world use cases
Common mistakes and fixes
6οΈβ£ String Indexing in Python
Zero-based indexing
Negative indexing
Index reference table
IndexError example
Indexing in loops
Strings are immutable (read-only)
7οΈβ£ String Slicing in Python
Basic slicing:
[start:stop]Why stop index is excluded
Negative slicing
Slicing with step:
[start:stop:step]
8οΈβ£ Real-World Use Cases for String Methods
.split(),.join(),.strip(),.replace().upper(),.lower(),.capitalize(),.title().startswith(),.endswith(),.find(),.count().isdigit(),.isalpha()
9οΈβ£ User Input in Python
How
input()worksπ Type conversion (
int(),float(),str())β¨ Cleaning input:
.strip(),.capitalize()β Validation:
.isdigit()for numbers.isalpha()for letters
β Real-world input with
.split()
π Escape Characters in Strings
\nβ New line\tβ Tab\\β Backslash\'β Single quote\"β Double quote
1οΈβ£1οΈβ£ Multi-line Strings in Python ("""...""")
Triple double or single quotes
Preserving line breaks
Practical example with message formatting
1οΈβ£ What is a String?
A string is text in Python. You create it using quotes:
You can use single or double quotes, but they must match.
text1 = "Hello"
text2 = 'World'
print(text1, text2)
Output:
Hello World
Also, when you use input() in Python, it always returns a string, even if the user types a number.
2οΈβ£ Python String Formatting Methods
There are 3 main ways to insert variables into strings:
| Method | Introduced In | Description |
% operator | Python 2.x | Oldest method (C-style formatting) |
.format() | Python 2.6+ | More readable and flexible |
f-strings | Python 3.6+ | Most modern, readable, and fastest |
1. % Formatting (C-style)
name = "Lorenzo"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is Lorenzo and I am 25 years old.
π§ Format Specifiers for % Formatting
| Specifier | Meaning |
%s | String |
%d | Integer (decimal) |
%f | Float (decimal) |
2. .format() Method
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Lorenzo and I am 25 years old.
print("My name is {0} and I'm {1}. {0} is learning Python.".format(name, age))
Output:
My name is Lorenzo and I'm 25. Lorenzo is learning Python.
3. f-Strings (Modern and Best)
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Lorenzo and I am 25 years old.
print(f"Next year, Iβll be {age + 1}")
Output:
Next year, Iβll be 26
β Summary Table: Python String Formatting Styles
| Style | Example | Use When... |
% | "Hello %s" % name | Reading or maintaining older code |
.format() | "Hello {}".format(name) | You need reusable or numbered placeholders |
f-strings | f"Hello {name}" | You're using Python 3.6 or newer (recommended) |
π§΅ Important Python String Methods
| Method | Example | What It Does |
.split() | "a b c".split() | Splits a string into a list |
.join() | " ".join(["a", "b", "c"]) | Joins a list into a single string |
.strip() | " hello ".strip() | Removes leading/trailing whitespace |
.replace() | "hi".replace("h", "b") | Replaces part of a string |
.upper() | "abc".upper() | Converts to uppercase |
.lower() | "ABC".lower() | Converts to lowercase |
.capitalize() | "hello".capitalize() | Capitalizes the first letter only |
.title() | "hello world".title() | Capitalizes the first letter of every word |
.startswith() | "python".startswith("py") | Checks if string starts with something (True/False) |
.endswith() | "data.csv".endswith(".csv") | Checks if string ends with something (True/False) |
.find() | "hello".find("l") | Returns the index of first match or -1 if not found |
.count() | "banana".count("a") | Counts how many times a character appears |
.isdigit() | "123".isdigit() | Checks if the string contains only digits |
.isalpha() | "abc".isalpha() | Checks if the string contains only letters |
π€ String Operations in Python
| Operation | Example | Result |
| Concatenation | "Hello" + " World" | 'Hello World' |
| Repetition | "Hi" * 3 | 'HiHiHi' |
| Length | len("Python") | 6 |
| Indexing | "Python"[0] | 'P' |
| Slicing | "Python"[1:4] | 'yth' |
| Uppercase | "hello".upper() | 'HELLO' |
| Lowercase | "HELLO".lower() | 'hello' |
| Replace | "Hello".replace("l", "z") | 'Hezzo' |
3οΈβ£ String Concatenation in Python
π Definition:
Joining two or more strings together using the + operator.
β Example:
greeting = "Hello"
name = "Lorenzo"
message = greeting + " " + name
print(message) # Output: Hello Lorenzo
Output:
Hello Lorenzo
β Mixing Strings with Other Data Types
You must convert non-strings before concatenating:
age = 25
# print("Age: " + age) # β Error!
print("Age: " + str(age)) # βοΈ Correct
Output:
Age: 25
π₯΅ Confusing Commas with + in print()
,adds spaces automatically+does not
name = "Lorenzo"
print("Hello", name) # βοΈ Output: Hello Lorenzo
print("Hello" + name) # βοΈ Output: HelloLorenzo
print("Hello" + " " + name) # βοΈ Output: Hello Lorenzo
Output:
Hello Lorenzo
HelloLorenzo
Hello Lorenzo
πͺ Accidental Line Breaks or Extra Spaces
Using backslash (\) to continue line:
message = "Hello " + \
"there!"
print(message)
Output:
Hello there!
Invalid example (line break without \):
'''
bad_message = "Hello "
+ "there!" # β SyntaxError
'''
Better: use parentheses:
message1 = ("This is a "
"clean and readable "
"way to concatenate.")
print(message1)
Output:
This is a clean and readable way to concatenate.
β
Better Alternatives: f-Strings and .format()
name = "Lorenzo"
age = 25
print("Name: " + name + ", Age: " + str(age))
Output:
Name: Lorenzo, Age: 25
Using f-strings:
print(f"Name: {name}, Age: {age}")
Output:
Name: Lorenzo, Age: 25
Using .format():
print("Name: {}, Age: {}".format(name, age))
Output:
Name: Lorenzo, Age: 25
π Summary Table
π§Ή String Concatenation Methods in Python
| Method | Description | Good For |
+ operator | Simple joins, but limited to strings | Small programs |
join() | Efficient for joining lists of strings | Loops, file content |
f-strings | Most readable and flexible | All modern Python (3.6+) |
format() | Useful for formatting numbers/strings | When f-strings not used |
4οΈβ£ String Repetition in Python
In Python, you can repeat a string multiple times using the * operator:
Syntax:
string * number
β Examples:
print("Hi" * 3) # Output: HiHiHi
print("=-" * 5) # Output: =-=-=-=-=-
print("Hello\n" * 2) # Output: Hello\nHello
Output:
HiHiHi
=-=-=-=-=-
Hello
Hello
π« Pitfalls to Avoid:
# "Hello" * "3" β TypeError
# "Hello" * 2.5 β TypeError
You can only multiply a string by an integer, not a string or float.
π― Works with print() Tricks
print("\n" * 3) # Adds 3 blank lines
print("π" * 5) # Repeats emoji 5 times
Output:
πππππ
5οΈβ£ Measuring String Length with len()
The len() function returns the number of characters in a string β including letters, spaces, and emojis.
β Examples:
print(len("Python")) # 6
print(len("Hello World")) # 11
print(len("12345")) # 5
print(len("") ) # 0 (empty string)
print(len("ππ₯")) # 2 (each emoji counts as one)
Output:
6
11
5
0
2
π§ Useful in Real Life:
Input validation (e.g., max 10 characters)
Password length checking
Looping through characters
Checking if a string is empty:
if len(text) == 0:
print("Empty!")
β οΈ Common Mistakes to Avoid:
| Mistake | Problem | Fix |
len["Hello"] | β TypeError (wrong syntax) | β
Use parentheses: len("Hello") |
Using len() on None | β TypeError | β
Check with if string: |
| Counting words | β Counts characters | β
Use .split() then len() |
β Counting Words in a Sentence:
sentence = "This is Python"
print(len(sentence.split())) # Output: 3 words
Output:
3
β Summary
len()counts characters, not words (unless used with.split()).Works with strings, lists, tuples, and more.
6οΈβ£ String Indexing in Python
Indexing means accessing individual characters in a string using their position (index).
Python uses zero-based indexing:
Index
0is the first characterIndex
1is the second, and so on
β Examples:
text = "Python"
print(text[0]) # P
print(text[1]) # y
print(text[5]) # n
Output:
P
y
n
π§ Negative Indexing
Python also supports negative indexing to count from the end:
text = "Python"
print(text[-1]) # n
print(text[-2]) # o
print(text[-6]) # P
Output:
n
o
P
π’ String Index Reference Table
| Character | P | y | t | h | o | n |
| Index (Positive) | 0 | 1 | 2 | 3 | 4 | 5 |
| Index (Negative) | -6 | -5 | -4 | -3 | -2 | -1 |
β οΈ IndexError Example
text = "Python"
print(text[10]) # β IndexError: string index out of range
Indexing only works on sequences like:
str,list,tuple,range
β Indexing in Loops
word = "Test"
for i in range(len(word)):
print(word[i])
Output:
T
e
s
t
π§ Note: Strings are immutable in Python β you cannot change a character using indexing:
word = "Hi"
word[0] = "B" # β TypeError
7οΈβ£ String Slicing in Python
Slicing lets you extract a portion (or "slice") of a string by specifying:
string[start:stop]
start: index where the slice begins (inclusive)stop: index where the slice ends (exclusive)If you skip one, Python uses defaults
β Examples:
text = "Python"
print(text[1:4]) # 'yth' β characters at index 1, 2, 3
print(text[:3]) # 'Pyt' β from beginning to index 2
print(text[3:]) # 'hon' β from index 3 to end
print(text[:]) # 'Python' β entire string
Output:
yth
Pyt
hon
Python
π€ Why Does Python Include the Start But Exclude the End?
text = "Python"
print(text[1:4]) # 'yth'
Includes index 1 β 'y'
Includes index 2 β 't'
Includes index 3 β 'h'
Excludes index 4 β 'o' is not included
π§ Negative Indexing Works Too:
text = "Python"
print(text[-3:]) # 'hon'
print(text[:-2]) # 'Pyth'
Output:
hon
Pyth
π§ General Syntax: string[start:stop:step]
startβ where to begin (inclusive)stopβ where to end (exclusive)stepβ how many steps to move (positive or negative)
β Step-Based Slicing Examples:
text = "Python"
print(text[::-1]) # 'nohtyP' β Reversed string
print(text[::2]) # 'Pto' β Every 2nd character from start
print(text[1:5:2]) # 'yh' β From index 1 to 4, every 2nd char
Output:
nohtyP
Pto
yh
π Use slicing often when you need substrings, reversals, or selective skipping.
8οΈβ£ Real-World Use Cases for String Methods
| Method | Example | Result | Use Case |
.split() | "John,Doe,30".split(",") | ['John', 'Doe', '30'] | Parsing CSV-formatted user data from a file or API |
.join() | ", ".join(["apple", "banana"]) | 'apple, banana' | Displaying a product list in a shopping cart summary |
.strip() | " user123 ".strip() | 'user123' | Cleaning form inputs before storing in a database |
.replace() | "pass123".replace("pass", "***") | '***123' | Masking sensitive data (like passwords or IDs) in logs |
.upper() | "lorenzo".upper() | 'LORENZO' | Standardizing usernames or country codes before saving |
.lower() | "USER@EMAIL.COM".lower() | 'user@email.com' | Normalizing emails for case-insensitive login validation |
.capitalize() | "python is great".capitalize() | 'Python is great' | Formatting short descriptions in blog previews |
.title() | "the great gatsby".title() | 'The Great Gatsby' | Displaying book or article titles in a reading app |
.startswith() | "https://example.com".startswith("https://") | True | Verifying URL security before redirecting or scraping |
.endswith() | "resume.pdf".endswith(".pdf") | True | Validating uploaded documents to allow only PDFs |
.find() | "support@email.com".find("@") | 7 | Validating email syntax by checking position of "@" |
.count() | "banana".count("a") | 3 | Counting keyword frequency in reviews for sentiment scoring |
.isdigit() | "12345".isdigit() | True | Verifying that age or phone number fields contain only digits |
.isalpha() | "Lorenzo".isalpha() | True | Validating names to ensure no numbers or special characters |
njk
9οΈβ£ User Input in Python
The input() function allows you to take text input from the user during a programβs execution.
When this runs, Python:
Shows the message (prompt)
Waits for the user to type something
Stores the input as a string, even if it looks like a number.
age = input("How old are you? ")
print("You are", age, "years old.")
User Input: 23
Example Output:
How old are you? 23
You are 23 years old.
π Converting Input to Numbers
When you use input(), the result is always a string β even if the user enters a number. To use the input as a number, convert it:
| Conversion | Example | Resulting Type |
int() | int("25") β 25 | Integer |
float() | float("3.14") β 3.14 | Float |
str() | str(42) β "42" | String |
birth_year = input("Enter your birth year: ")
age = 2025 - int(birth_year)
print("You are", age, "years old.")
User Input: 1987
Output:
Enter your birth year: 1987
You are 38 years old.
β¨ Cleaning and Formatting Input
Use .strip() and .capitalize() to clean and format raw user input:
raw_name = input("Enter your first name: ")
# Clean and format the input
cleaned_name = raw_name.strip().capitalize()
print("Hello,", cleaned_name)
User Input: lorenzo nicholas
Output:
Enter your first name: lorenzo nicholas
Hello, Lorenzo nicholas
β Example 1: Validating Age Input (Check if Input Is a Number)
age_input = input("Enter your age: ")
if age_input.isdigit():
age = int(age_input)
print("You will be", age + 1, "next year.")
else:
print("β Invalid input. Please enter a number.")
User Input: dg
Output:
Enter your age: dg
β Invalid input. Please enter a number.
β Example 2: Validating a Name Field (Only Letters Allowed)
name = input("Enter your first name: ")
if name.isalpha():
print("Hello,", name.capitalize())
else:
print("β Names should only contain letters. Try again.")
User Input: xdgx
Output:
Enter your first name: xdgx
Hello, Xdgx
β Real-World Example: Taking Subject Marks in One Line
marks_input = input("Enter your marks for Math, Science, and English (separated by spaces): ")
# Split the input into separate values
marks = marks_input.split()
# Convert strings to integers
math, science, english = int(marks[0]), int(marks[1]), int(marks[2])
# Calculate average
average = (math + science + english) / 3
print("Average mark:", round(average, 2))
User Input: 34 56 89
Output:
Enter your marks for Math, Science, and English (separated by spaces): 34 56 89
Average mark: 59.67
π Escape Characters in Strings
Escape characters start with a backslash \ and tell Python to treat the next character in a special way.
| Escape | Meaning | Example Code | Output |
\n | New line | print("Hello\nWorld") | HelloWorld |
\t | Horizontal tab (indent) | print("Name:\tLorenzo") | Name: Lorenzo |
\\ | Backslash character (\) | print("Path: C:\\User\\Files") | Path: C:\User\Files |
\' | Single quote | print('It\'s Python') | It's Python |
\" | Double quote | print("She said: \"Hello\"") | She said: "Hello" |
πΉ \n β New Line
print("Hello\nWorld")
Output:
Hello
World
πΉ \t β Horizontal Tab
print("Name:\tLorenzo")
Output:
Name: Lorenzo
πΉ \\ β Backslash Character
print("Path: C:\\User\\Files")
Output:
Path: C:\User\Files
πΉ \' β Single Quote Inside Single-Quoted String
print('It\'s Python')
Output:
It's Python
πΉ \" β Double Quote Inside Double-Quoted String
print("She said: \"Hello\"")
Output:
She said: "Hello"
1οΈβ£1οΈβ£ Multi-line Strings in Python ("""...""")
Multi-line strings allow you to store or display text that spans multiple lines without needing \n manually.
You can define them using:
"""Triple double quotes"""
'''Triple single quotes'''
β Line breaks are preserved as you write them.
Example:
message = """Dear Lorenzo,
Thank you for registering.
We hope you enjoy the course.
Regards,
Team Python
"""
print(message)
Output:
Dear Lorenzo,
Thank you for registering.
We hope you enjoy the course.
Regards,
Team Python