0% found this document useful (0 votes)
7 views16 pages

Understanding Strings in Python

String notes

Uploaded by

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

Understanding Strings in Python

String notes

Uploaded by

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

String

• A string is a sequence of characters


that represents text. • What can a string
• Simple explanation 😊
• 👉 String = Text / Words / Sentence contain?
• Examples: • Letters → "abc"
• "Hello"
• "Dollcy"
• Numbers → "123"
• "12345" • Symbols → "@#₹!"
• "Hello World!"
• In Programming (Python):
• Spaces → "Hello World"
• Strings are always written inside • Real-life examples:
quotes
– Single quotes ' '
• Your name
– Double quotes " " • WhatsApp message
• name = "Dollcy" message = 'I love
coding' • Passwords (in text form)
Indexing of a string
• Indexing of a string means the
position number of each
character in the string. Each
position is called an index.
• Key points:
• Indexing starts from 0.
• Positive index → count from
the start of the string
• Negative index → count from
the end of the string (-1 is the
last character)
• Example:
• text = “HELLO PYTHON"
EXAMPLE
• text = "Python"
• print(text[0]) # P
• print(text[5]) # n
• print(text[-1]) # n
• print(text[-6]) # P
ASCII and Unicode in Python
• 11️⃣What is ASCII?
• ASCII (American Standard Code for Information Interchange) is a character encoding system that represents characters using numbers.
• Total characters: 128
• Range: 0 to 127
• Includes:
– English letters (A–Z, a–z)
– Digits (0–9)
– Special symbols (@, #, $, etc.)
• Example in Python:
• print(ord('A'))
• Output:
• 65
• 👉 ord() returns the ASCII value of a character.
• print(chr(65))
• Output:
• A
• 👉 chr() converts a number into its corresponding character.
• 2️⃣What is Unicode?
• Unicode is an advanced character encoding system.
• Supports all languages of the world
• Includes:
– Hindi (अ, क)
– Chinese ( 你 )
– Emojis (😊 ❤️)
• Unicode has more than 1 million characters
• 👉 In Python 3, all strings are Unicode by default.
String Operators in Python
• Python provides different operators to • 33️⃣Indexing Operator ([])
work with strings.
• Used to access characters using index
• 1 Concatenation Operator (+)
1️⃣ number.
• Used to join two or more strings. • Index starts from 0
• Example: • Example:
• s1 = "Hello" s2 = "World" result = s1 + • s = "Python" print(s[0]) print(s[3])
" " + s2 print(result)
• Output:
• Output:
• Ph
• Hello World
• 4️⃣Membership Operators (in, not in)
• Used to check whether a substring is
• 2️⃣Repetition Operator (*)
present or not.
• Used to repeat a string multiple times.
• Example:
• Example:
• s = "Python" print("Py" in s)
• s = "Hi " print(s * 3) print("Java" not in s)
• Output: • Output:
• Hi Hi Hi • True True
• 66️⃣Comparison Operators (==, !=,
<, >)
• 🔑 Important Points
• Used to compare strings. • Strings are immutable
• Example: (cannot be changed).
• a = "apple" b = "banana" print(a
== b) print(a < b)
• Indexing starts from 0.
• Output: • + joins strings.
• False True
• * repeats strings.
• 7️⃣Assignment Operator (=)
• Used to assign a string to a
variable.
• Example:
• name = “PYTHON" print(name)
String Slicing in Python
• String slicing is used to extract a part of a • 44️⃣Using Negative Index
string. • s = "Python" print(s[-4:-1])
• Syntax: • Output:
• string[start : end : step] • tho
• start → index to begin (inclusive) • 5️⃣Slicing with Step
• end → index to stop (exclusive) • s = "Python" print(s[0:6:2])
• step → gap between characters (optional)
• Output:
• 1 Basic Slicing
1️⃣
• Pto
• s = "Python" print(s[0:4])
• 6️⃣Reverse a String
• Output:
• s = "Python" print(s[::-1])
• Pyth
• Output:
• 2️⃣Slice from a Position to End
• nohtyP
• s = "Python" print(s[2:])
• Output:
• Important
7️⃣ Points
• thon
• Index starts from 0
• 3️⃣Slice from Beginning to a Position • Ending index is not included
• s = "Python" print(s[:5]) • Negative index starts from -1 (last
• Output:
character)
• Pytho
• Strings are immutable
String Functions in Python
• 6. swapcase()
• 🔤 String Functions in Python (Short • Changes upper to lower and vice-versa
Notes) • "HeLLo".swapcase() # hEllO
• 1. len() • 7. strip()
• Returns length of string • Removes spaces from both sides
• " hi ".strip() # hi
• len("Python") # 6
• 8. lstrip()
• 2. lower() • Removes left spaces
• Converts to lowercase • " hi".lstrip() # hi
• "HELLO".lower() # hello • 9. rstrip()
• Removes right spaces
• 3. upper()
• "hi ".rstrip() # hi
• Converts to uppercase • 10. replace()
• "hello".upper() # HELLO • Replaces substring
• 4. capitalize() • "hello".replace("h","H") # Hello
• 11. find()
• Capitalizes first letter • Returns index of substring
• "python".capitalize() # Python • "python".find("t") # 2
• 5. title() • 12. index()
• Capitalizes first letter of each word • Same as find (gives error if not found)
• "python".index("o") # 4
• "python language".title() # Python
Language
• 13. count() • 18. isalpha()
• Counts occurrences • Checks only letters
• • "abc".isalpha() # True
"banana".count("a") # 3
• 19. isdigit()
• 14. startswith()
• Checks only digits
• Checks starting word • "123".isdigit() # True
• "python".startswith("py") # True • 20. isalnum()
• 15. endswith() • Checks letters + digits
• Checks ending word • "abc123".isalnum() # True
• "python".endswith("on") # True • 21. isspace()
• 16. split() • Checks only spaces
• • " ".isspace() # True
Splits string into list
• "a b c".split() # ['a','b','c']
• ⭐ Important Note
• 17. join() • Strings are immutable
• Joins list into string • Functions return new string, original string
• "-".join(["a","b"]) # a-b remains same
PROGRAMS
1 .#Find the length of a 2.#Length of Each Word
string • s = "Python is easy"
• s = input("Enter • for w in [Link]():
string: /n") print(w, ":",
• print(len(s)) len(w))
• OUTPUT • OUTPUT
Enter string • Python : 6
HELLO • is : 2
5 • easy : 4
3.⃣ Count Vowels and Consonants
• s = input("Enter string: ")
• u=l=0

• for ch in s:
• if [Link]():
• u += 1
• elif [Link]():
• l += 1

• print("Uppercase:", u)
• print("Lowercase:", l)
• .️⃣. Reverse a String
.4
• s = "Hello"
print(s[::-1]) • #6. Check Palindrome
• output
olleH • s = "madam"
• # 5. Count Uppercase and Lowercase • if s == s[::-1]:
• s = "PyThOn"
• u=l=0
• print("Palindrome")


for ch in s: • else:
if [Link]():
• u += 1 • print("Not Palindrome")
• elif [Link]():
• l += 1
• print("Upper:", u)
• print("Lower:", l) • # Output:


# Output:
# Upper: 3
• # Palindrome
• # Lower: 3
• # 8. Capitalize First
• # 7. Count Digits Letter of Each Word
• s = "abc123" • s = "python language"
• d=0 • print([Link]())
• for ch in s: • # Output:
• if [Link](): • # Python Language
• d += 1
• print(d)
• # Output:
• #3
• 9. Find Substring • 10. Replace Word
• s = "Python" • s = "This is bad"
• sub = "th" • print([Link]("bad",
• if sub in s: "good"))
• print("Found") • # Output:
• else: • # This is good
• print("Not Found")
• # Output:
• # Found
# Find the longest word in a string

• s = "Python programming is very easy"

• words = [Link]()
• longest = ""

• for w in words:
• if len(w) > len(longest):
• longest = w

• print("Longest word:", longest)


• print("Length:", len(longest))

• # Output:
• # Longest word: programming
• # Length: 11
• Write a program that • s = input("Enter a string: ")
ask the user for a string • c = input("Enter a character to
search: ")
s and a character C
then it print out the
• print("Locations of
location of each character:", c)
character c in the string
s • for i in range(len(s)):
• if s[i] == c: # Check
each character
• print(i) # Print
location (index)

You might also like