String Functions
String Functions
Stri Length
ng
Thelen() function returns
length
the of a string.
#Program to findlength
the of a string
= "Hello, World!"
string
= len(string)
length
print("The
length of the string is: {length}")
Output:
2. String Concatenation
str1 "Hello"
=
str2= "World"
Output:
Hello World
Concatenated string:
3. String Case Conversion
print("Uppercase:", string.upper())
print("Lowercase:", string.lower())
Output:
PROGRAMMING
Uppercase: PYTHON
4.String Slicing
= "Hello, World!"
string
sliced_string = string[0:5]
# Extract characters from index 0 to 4
Output:
Hello
Sliced string:
5. String Replace
Output:
6. String Strip
The strip(),
lstrip(), and rstrip() functions remove whitespace from the beginning or end o
string.
print("After
lstrip:", repr(string.lstrip()))
Output:
Original
string:
' Hello, World! '
After strip:
'Hello, World!'
'Hello, World!
Afterlstrip: '
After rstrip:
' Hello, World!'
7. Check Substring
= "Hello, World!"
string
if "World" in string:
else:
Output:
split_string = string.split()
# Split by spaces
joined_string = "-".join(split_string)
# Join with a hyphen
Output:
The find() function returns the index of the first occurrence of aifsubstring,
not found.or -1
= "Hello, World!"
string
position = string.find("World")
if position
!= -1:
else:
Output:
string = "banana"
count = string.count("a")
print(f"The
letter 'a' appears {count} times in the word 'banana'.")
Output: