KEMBAR78
Unit 2 - Strings in Python HPTU | PDF | String (Computer Science) | Letter Case
0% found this document useful (0 votes)
6 views7 pages

Unit 2 - Strings in Python HPTU

Uploaded by

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

Unit 2 - Strings in Python HPTU

Uploaded by

palakchauhan006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Strings in Python:

A string in Python is a sequence of characters enclosed within single


quotes ' ', double quotes " ", or triple quotes ''' ''' / """ """.

1. Creating Strings
str1 = 'Hello'
str2 = "World"
str3 = '''Python is fun!'''
Python strings are immutable, meaning once created, their content cannot be
changed.

Sorting Strings
Sorting a string means rearranging its characters in a specific order—typically
alphabetical (lexicographical).

🔹 a. Using sorted() Function


s = "python"

sorted_s = sorted(s)

print(sorted_s) # Output: ['h', 'n', 'o', 'p', 't', 'y']

print(''.join(sorted_s)) # Output: 'hnopty'

●​ sorted() returns a list of characters in sorted order.​

●​ ''.join() converts the list back into a string.

🔹 b. Case Sensitivity
s = "PyThOn"

print(''.join(sorted(s))) # Output: 'OPTPhny'


By default, uppercase letters come before lowercase (ASCII order).

To ignore case, convert to lowercase before sorting:

s = "PyThOn"

sorted_s = ''.join(sorted(s.lower()))

print(sorted_s) # Output: 'hnopty'

🔹 c. Custom Sorting Using key


s = "PyThOn"

print(''.join(sorted(s, key=str.lower)))

# Output: 'hOnPTy'

This keeps the original casing but sorts alphabetically (case-insensitive).

🔹 d. Descending Order
s = "computer"

print(''.join(sorted(s, reverse=True)))

# Output: 'utropmec'

🔹 e. Sorting Words in a String


If you want to sort words, not characters:

Example 1:

sentence = "python is a powerful language"

words = sentence.split()
sorted_words = sorted(words)

print(" ".join(sorted_words))

Output: a is language powerful python

Example 2: Join String from list data

words = ['Hello', 'Python', 'World']

result = " ".join(words)

print(result)

Output: Hello Python World

2. Accessing String Characters


Use indexing (starts from 0):

text = "Python"
print(text[0]) # P
print(text[-1]) # n (last character)

3. String Slicing
String [start:end:step] or slice(start,end,step)

●​ start: The index to begin slicing (inclusive). Default is 0.​

●​ end: The index to end slicing (exclusive). Default is the length of the string.​

●​ step: How many characters to move forward (or backward) at a time.


Default is 1.​
s = "PythonProgramming"
print(s[0:6]) # Python
print(s[6:]) # Programming
print(s[:]) # Full string
print(s[::-1]) # Reversed

4. String Operations

Operation Example Result

Concatenation 'Hello ' + 'World' 'Hello World'

Repetition 'Hi! ' * 3 'Hi! Hi! Hi! '

Membership 'Py' in 'Python' True

Length len("Python") 6

a = "Hello"
b = "World"
result = a + " " + b
print(result) # Output: Hello World

text = "Hi! "


print(text * 3) # Output: Hi! Hi! Hi!

name = "Python Programming"


print("Python" in name) # True
print("Java" not in name) # True

msg = "Hello!"
print(len(msg)) # Output: 6
5. Common String Methods
lower() Converts all characters to lowercase.
upper() Converts all characters to uppercase.
strip() method is used to remove leading and trailing whitespace characters (including
spaces, tabs, and newlines) from a string.
replace() method is used to replace parts of a string with another string.
split() method is used to split a string into a list of substrings, based on a separator.
find() method searches for a substring within a string and returns the index of its first
occurrence. If the substring is not found, it returns -1.
count() method returns the number of times a specified substring appears in a string.

s = " Hello Python "

print(s.lower()) # hello python


print(s.upper()) # HELLO PYTHON
print(s.strip()) # "Hello Python"
print(s.replace("Python", "World")) # Hello World
print(s.split()) # ['Hello', 'Python']
print(s.find("Python")) # 7 returns starting index
print(s.count("l")) # 2
print(s.index("Python")) ​ ​ #7

Note: String methods do not modify the original string (strings


are immutable).

6. String Formatting

🔸 Old Style (%)


name = "Alice"
print("Hello, %s!" % name)

🔸 str.format()
print("Hello, {}!".format("Bob"))

🔸 f-strings (Python 3.6+)


age = 25
print(f"I am {age} years old")

7. Multiline Strings
text = """This is
a multi-line
string."""
print(text)

8. String Comparison
a = "Apple"
b = "Banana"
print(a == b) # False
print(a < b) # True (lexicographic order)

9. String Iteration
for char in "Python":
print(char)

Conclusion:
Operation Syntax / Example Description

Length len(s) Get string length

Index s[0] Access character

Slice s[1:4] Substring


Replace s.replace('a','b') Replace substrings

Split s.split() Break string into list

Join ' '.join(list) Combine list into string

Case s.lower(), Change case


s.upper()

Strip s.strip() Remove whitespace

text = "Hello!"
vowel_count = 0

for char in text:


if char.lower() in "aeiou":
vowel_count += 1

print("Number of vowels:", vowel_count)

You might also like