Print function and String manipulation in python


Basic Print Statements

Demonstrates printing of various data types and multiple items in one statement.

print("Hello")  # String print
print(5)        # Integer
print(4.12)     # Float
print("Hi", 2, 5.7, "Are you good?")
print('Hi, there')
print("Print single inverted comma ' within a string by surrounding the whole string with double inverted comma")
Output:
Hello
5
4.12
Hi 2 5.7 Are you good?
Hi, there
Print single inverted comma ' within a string by surrounding the whole string with double inverted comma

f-String Example

Shows how to embed variables directly inside strings using f-strings for clearer and cleaner formatting.

string_variable = "Alex"
int_variable = 10
print(f"The age of {string_variable} is {int_variable}.")  # f-string literal

Output:
The age of Alex is 10.

Escape Characters

Sometimes you need to include special characters in strings, such as quotes, new lines, or tabs. Python allows this using escape sequences, which start with a backslash (\). Below are a few commonly used escape characters:

print("She said, \"Hello!\" with a smile.")    # Prints a quote inside a string
print("This is line one.\nThis is line two.")  # Creates a new line
print("Column1\tColumn2\tColumn3")             # Adds a tab space between columns

Output:
She said, “Hello!” with a smile.
This is line one.
This is line two.
Column1 Column2 Column3

Multiline Strings

How to create strings spanning multiple lines using triple quotes.

string_with_multiple_lines = '''line1,
      line2,
      line3,
      line4'''
print(string_with_multiple_lines)

Output:
line1,
line2,
line3,
line4

String Indexing & Length

Access individual characters by index and find the length of a string.

example_string = "Hey! How are you?"
print("Length of the example string is:", len(example_string))
print("The first character of example_string is:", example_string[0])
print("The second character of example_string is:", example_string[1])
print("The last character using hardcoded index:", example_string[16])
print("The last character using negative indexing:", example_string[-1])  # Negative indexing
print("The second last character using negative indexing:", example_string[-2])

Output:
Length of the example string is: 17
The first character of example_string is: H
The second character of example_string is: e
The last character using hardcoded index: ?
The last character using negative indexing: ?
The second last character using negative indexing: u

Membership Testing

Check if a substring exists or does not exist in a string.

example_string = "Hey! How are you?"
print("Is the letter 'r' in the example_string?", 'r' in example_string)
print("Is the word 'there' NOT in the example_string?", 'there' not in example_string)

Output:
Is the letter ‘r’ in the example_string? True
Is the word ‘there’ NOT in the example_string? True

String Concatenation and Type Casting

Combine strings using + operator and convert other types to strings for concatenation.

person1 = "John"
age1 = 10
person2 = "George"
age2 = 11
print(person1 + " and " + person2 + " are two friends")
print(person1 + "'s age is " + str(age1) + " and " + person2 + "'s age is " + str(age2))

# Note: Direct concatenation of string and int without casting will cause an error.
# Uncommenting the line below will raise an error:
# print(person1 + "'s age is " + age1 + " and " + person2 + "'s age is " + age2)

Output:
John and George are two friends
John’s age is 10 and George’s age is 11
Uncomment the last line and execute.  It will throw this type of error.
Traceback (most recent call last):
File “c:\Users\<username>\Documents\Python Scripts\test.py”, line 10, in <module>
print(person1 + “‘s age is ” + age1 + ” and ” + person2 + “‘s age is ” + age2)
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
TypeError: can only concatenate str (not “int”) to str

String Methods

Common useful methods to change case, replace substrings, and find indexes.

sample = "Python Programming"
print(sample.upper())
print(sample.lower())
print(sample.replace("Python", "Java"))
print("Index of 'gram':", sample.find("gram"))

Output:
PYTHON PROGRAMMING
python programming
Java Programming
Index of ‘gram’: 10

Splitting String into Words

Split sentences into words and iterate through them.

sentence = "Hey there! How are you doing today?"
words = sentence.split()
print("Words in the sentence:")
for word in words:
    print(word)

Output:
Words in the sentence:
Hey
there!
How
are
you
doing
today?

String Slicing

Extract substrings using slice notation.

text = "Hello, World!"
print("First 5 characters:", text[:5])
print("Characters from index 7 to end:", text[7:])
print("Every second character:", text[::2])

Output:
First 5 characters: Hello
Characters from index 7 to end: World!
Every second character: Hlo ol!

Multiline f-String Example

Combine multiline strings and f-string formatting for clean, readable output.

name = "Alice"
age = 25
city = "New York"
print(f"""Profile:
Name: {name}
Age: {age}
City: {city}
""")

Output:
Profile:
Name: Alice
Age: 25
City: New York

Taking Input from User

Example of taking user input and using it in output (commented out for easy activation).

user_name = input("Enter your name: ")
print(f"Nice to meet you, {user_name}!")

Output:
Enter your name: Alex
Nice to meet you, Alex!

Extra String Methods

Trim whitespace and check string properties like alphanumeric, digits, startswith, and endswith.

misc = "  Hello123  "  # String with leading and trailing spaces
trimmed = misc.strip()

print("Trimmed string:", trimmed)
print("Does it start with 'He'? ->", trimmed.startswith("He"))
print("Is the trimmed string alphanumeric? ->", trimmed.isalnum())
print("Is the string alphabetic only? ->", trimmed.isalpha())  # False because it contains digits
print("Is the string made of digits only? ->", trimmed.isdigit())  # False because it contains letters
print("Does it end with '123'? ->", trimmed.endswith("123"))

Output:
Trimmed string: Hello123
Does it start with ‘He’? -> True
Is the trimmed string alphanumeric? -> True
Is the string alphabetic only? -> False
Is the string made of digits only? -> False
Does it end with ‘123’? -> True