Skip to main content

Command Palette

Search for a command to run...

🧡 Python Part 2: Strings and User Input in Python

Updated
β€’15 min readβ€’View as Markdown

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() 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 print

  • Accidental 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 \n and 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:

MethodIntroduced InDescription
% operatorPython 2.xOldest method (C-style formatting)
.format()Python 2.6+More readable and flexible
f-stringsPython 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

SpecifierMeaning
%sString
%dInteger (decimal)
%fFloat (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

StyleExampleUse When...
%"Hello %s" % nameReading or maintaining older code
.format()"Hello {}".format(name)You need reusable or numbered placeholders
f-stringsf"Hello {name}"You're using Python 3.6 or newer (recommended)

🧡 Important Python String Methods

MethodExampleWhat 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

OperationExampleResult
Concatenation"Hello" + " World"'Hello World'
Repetition"Hi" * 3'HiHiHi'
Lengthlen("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

MethodDescriptionGood For
+ operatorSimple joins, but limited to stringsSmall programs
join()Efficient for joining lists of stringsLoops, file content
f-stringsMost readable and flexibleAll modern Python (3.6+)
format()Useful for formatting numbers/stringsWhen 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:

MistakeProblemFix
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 0 is the first character

  • Index 1 is 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

CharacterPython
Index (Positive)012345
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



MethodExampleResultUse 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://")TrueVerifying URL security before redirecting or scraping
.endswith()"resume.pdf".endswith(".pdf")TrueValidating uploaded documents to allow only PDFs
.find()"support@email.com".find("@")7Validating email syntax by checking position of "@"
.count()"banana".count("a")3Counting keyword frequency in reviews for sentiment scoring
.isdigit()"12345".isdigit()TrueVerifying that age or phone number fields contain only digits
.isalpha()"Lorenzo".isalpha()TrueValidating 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:

ConversionExampleResulting Type
int()int("25") β†’ 25Integer
float()float("3.14") β†’ 3.14Float
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.

EscapeMeaningExample CodeOutput
\nNew lineprint("Hello\nWorld")HelloWorld
\tHorizontal tab (indent)print("Name:\tLorenzo")Name: Lorenzo
\\Backslash character (\)print("Path: C:\\User\\Files")Path: C:\User\Files
\'Single quoteprint('It\'s Python')It's Python
\"Double quoteprint("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

More from this blog

Data Science

39 posts