0% found this document useful (0 votes)
2 views12 pages

Python Strings

Uploaded by

garimar629
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Python Strings

Uploaded by

garimar629
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Strings

1. Introduction to Strings

 A string in Python is a sequence of characters enclosed in single quotes (' '), double quotes
(" "), or triple quotes (''' ''' or """ """).

 Strings are immutable → once created, they cannot be changed (though new strings can be
formed).

Examples:

s1 = 'Hello'

s2 = "Python"

s3 = '''This is

a multi-line string

and this can be easily created in

python '''

print(s1, s2)

print(s3)

Quotes Inside Quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

2. Creating and Accessing Strings

 Strings are created by assigning text to a variable.

 We can access characters using indexing.

Examples:
text = "Python"

print(text[0]) # First character: P

print(text[2]) # Third character: t

print(text[-1]) # Last character: n

3. String Slicing

 Extracting parts of a string using [start:end:step].

 Start index is included, end index is excluded.

Examples:

word = "Programming"

print(word[0:6]) # Progra

print(word[:6]) # Progra

print(word[3:]) # gramming

print(word[::2]) # Pormig (step = 2)

print(word[::-1]) # gnimmargorP (reverse string)

4. String Operations

(a) Concatenation

a = "Hello"

b = "World"

print(a + " " + b) # Hello World

(b) Repetition

print("Hi! " * 3) # Hi! Hi! Hi!

(c) Membership

sentence = "Python is fun"

print("Python" in sentence) # True

print("Java" not in sentence) # True

5. String Functions & Methods

Python has many built-in methods to work with strings.

(a) Changing Case


text = "hello world"

print([Link]()) # HELLO WORLD

print([Link]()) # hello world

print([Link]()) # Hello World

print([Link]()) # Hello world

(b) Checking Type of Characters

data = "Python123"

print([Link]()) # False (contains numbers)

print([Link]()) # False (contains letters)

print("123".isdigit()) # True

print("hello".isalpha())# True

print(" ".isspace()) # True

(c) Searching & Counting

text = "I love Python, Python is great!"

print([Link]("Python")) # 7 (first occurrence)

print([Link]("Python")) # 14 (last occurrence)

print([Link]("Python")) # 2

(d) Replacing

msg = "I like Java"

print([Link]("Java", "Python")) # I like Python

(e) Splitting & Joining

line = "apple,banana,orange"

fruits = [Link](",") # ['apple', 'banana', 'orange']

print(fruits)

words = ["Python", "is", "fun"]

sentence = " ".join(words) # Python is fun

print(sentence)

(f) Stripping (Removing spaces or characters)

text = " hello "

print([Link]()) # 'hello'
print([Link]()) # 'hello '

print([Link]()) # ' hello'

6. String Formatting

 f-strings (Python 3.6+)- f-strings (formatted string literals) are one of Python’s most powerful
features. They let you embed expressions inside curly braces {} directly in a string.

Examples:

name = "Ram"

age = 25

print(f"My name is {name} and I am {age} years old") # f-string

example:

x = 10

y=5

print(f"The sum of {x} and {y} is {x + y}.")

print(f"{x} divided by {y} is {x / y}.")

Example:

pi = 3.14159265

print(f"Value of pi (2 decimal places): {pi:.2f}")

print(f"Value of pi (4 decimal places): {pi:.4f}")

Output

Value of pi (2 decimal places): 3.14

Value of pi (4 decimal places): 3.1416

Example:

def square(n):

return n * n
num = 6

print(f"The square of {num} is {square(num)}.")

Output:

The square of 6 is 36.

7. Iterating through Strings

text = "Python"

for ch in text:

print(ch)

8. Useful Built-in Functions

text = "Python"

print(len(text)) # 6

print(min(text)) # 'P' (based on ASCII)

print(max(text)) # 'y'

print(sorted(text))# ['P','h','n','o','t','y']

9. Escape Sequences

Used for special characters inside strings.

Escape Code Meaning

\n Newline

\t Tab space

\' Single quote

\" Double quote

\\ Backslash

Example:

print("Hello\nWorld") # Line break

print("Python\tRocks") # Tab
print("She said, \"Hi!\"")

10. Raw Strings

 Prefix with r to ignore escape sequences.

print(r"C:\new_folder\[Link]")

12. Mini Programs for Practice

1. Count vowels in a string.

2. Reverse a string without slicing.

3. Check if a string is a palindrome.

4. Word frequency counter (using split() + dictionary).

5. Replace spaces in a sentence with -.

Python Strings – Questions & Answers

Level 1: Basics

Q1. Create a string with your name and:

 Print the first character.

 Print the last character.

 Print the middle character.

Answer:

name = "Naman"

print("First:", name[0]) #N

print("Last:", name[-1]) #n

print("Middle:", name[len(name)//2]) # m

Q2. Extract parts of "Programming":

 First 5 characters.

 Last 4 characters.
 Characters from index 2 to 7.

Answer:

word = "Programming"

print(word[:5]) # Progr

print(word[-4:]) # ming

print(word[2:8]) # ogramm

Q3. Concatenate two strings: "Python" and "Rocks".

Answer:

a = "Python"

b = "Rocks"

print(a + " " + b) # Python Rocks

Q4. Repeat "Hello" 5 times.

Answer:

print("Hello " * 5) # Hello Hello Hello Hello Hello

Q5. Check if "fun" exists in "Python is fun to learn".

Answer:

sentence = "Python is fun to learn"

print("fun" in sentence) # True

Level 2: String Methods

Q6. Convert "python programming" into:

 UPPERCASE

 lowercase

 Title Case

Answer:

text = "python programming"

print([Link]()) # PYTHON PROGRAMMING

print([Link]()) # python programming


print([Link]()) # Python Programming

Q7. Check whether strings contain only alphabets, digits, or spaces.

Answer:

print("Hello".isalpha()) # True

print("12345".isdigit()) # True

print(" ".isspace()) # True

Q8. Count how many times "Python" occurs in "Python is easy. Python is powerful. Python is fun.".

Answer:

text = "Python is easy. Python is powerful. Python is fun."

print([Link]("Python")) # 3

Q9. Replace "Java" with "Python" in "I love Java".

Answer:

msg = "I love Java"

print([Link]("Java", "Python")) # I love Python

Q10. Split and join "apple,banana,grapes,orange".

Answer:

line = "apple,banana,grapes,orange"

fruits = [Link](",")

print(fruits) # ['apple', 'banana', 'grapes', 'orange']

sentence = " | ".join(fruits)

print(sentence) # apple | banana | grapes | orange

Level 3: Iteration and Functions

Q11. Count vowels in a string.

Answer:

text = "Python Programming"


vowels = "aeiouAEIOU"

count = 0

for ch in text:

if ch in vowels:

count += 1

print("Vowels:", count) # 4

Q12. Reverse a string without slicing.

Answer:

text = "Python"

rev = ""

for ch in text:

rev = ch + rev

print("Reversed:", rev) # nohtyP

Q13. Check if a string is palindrome.

Answer:

word = "madam"

if word == word[::-1]:

print("Palindrome")

else:

print("Not Palindrome")

Q14. Remove spaces from a string.

Answer:

text = "Python is fun"

print([Link](" ", "")) # Pythonisfun

Q15. Print each character with its index.

Answer:

text = "Hello"
for i in range(len(text)):

print(i, ":", text[i])

Level 4: Formatting & Escape Sequences

Q16. Print the following using escape sequences:

Hello

Python

Rocks!

Answer:

print("Hello\nPython\nRocks!")

Q17. Print name and age using three formatting methods.

Answer:

name = "Raman"

age = 25

print("My name is %s and I am %d years old" % (name, age))

print("My name is {} and I am {} years old".format(name, age))

print(f"My name is {name} and I am {age} years old")

Q18. Print:
She said, "Python is amazing!"

Answer:

print("She said, \"Python is amazing!\"")

Level 5: Mini-Programs

Q19. Word Frequency Counter.

Answer:

text = "Python is fun and Python is powerful"

words = [Link]()

freq = {}
for word in words:

freq[word] = [Link](word, 0) + 1

for w, c in [Link]():

print(w, ":", c)

Output:

Python : 2

is : 2

fun : 1

and : 1

powerful : 1

Q20. Find the longest word.

Answer:

sentence = "I am learning Python programming"

words = [Link]()

longest = max(words, key=len)

print("Longest word:", longest) # programming

Q21. Anagram Checker.

Answer:

word1 = "listen"

word2 = "silent"

if sorted(word1) == sorted(word2):

print("Anagram")

else:

print("Not Anagram")

Q22. Count words and characters.


Answer:

text = "Python is amazing"

print("Words:", len([Link]())) #3

print("Characters:", len(text)) # 16

Q23. Remove punctuation.

Answer:

import string

text = "Hello!!! Python, is great... right??"

cleaned = ""

for ch in text:

if ch not in [Link]:

cleaned += ch

print(cleaned) # Hello Python is great right

You might also like