DEV Community

Keerti Sadana S
Keerti Sadana S

Posted on

PYTHON - STRING METHODS EXAMPLES

Upper():

str1 =  "geeksforgeeks"
print(str1.upper())
Enter fullscreen mode Exit fullscreen mode

Output:
GEEKSFORGEEKS

Lower():

str = "GEEKSFORGEEKS"
print(str.lower())
Enter fullscreen mode Exit fullscreen mode

Output:
geeksforgeeks

Capitalize():

str1 =  "geeks for geeks"
print(str1.capitalize())
Enter fullscreen mode Exit fullscreen mode

Output:
Geeks for geeks

Title():

str1 =  "geeks for geeks"
print(str1.title())
Enter fullscreen mode Exit fullscreen mode

Output:
Geeks For Geeks

Split():

str1 =  "geeks for geeks"
print(str1.split())
Enter fullscreen mode Exit fullscreen mode

Output:
['geeks', 'for', 'geeks']

Join():

lst = ["Geeks", "For", "Geeks"]
print(' '.join(lst))
Enter fullscreen mode Exit fullscreen mode

Output:
Geeks For Geeks

Startswith():

str = "Kite"
print(str.startswith('K'))
Enter fullscreen mode Exit fullscreen mode

Output:
True

Endswith():

str = "Kite"
print(str.endswith('e'))
Enter fullscreen mode Exit fullscreen mode

Output:
True

Casefold():

str = "GEEKSFORGEEKS"
print(str.casefold())
Enter fullscreen mode Exit fullscreen mode

Output:
geeksforgeeks

Swapcase():

str = "Kite"
print(str.swapcase())
Enter fullscreen mode Exit fullscreen mode

Output:
kITE

Strip():

text = "   \n  Hello, Python!   \t "
cleaned = text.strip()
print(f"Original: '{text}'")
print(f"Cleaned:  '{cleaned}'")
Enter fullscreen mode Exit fullscreen mode

Output:
Original: '

Hello, Python! '
Cleaned: 'Hello, Python!'

Lstrip():

text = "   \n\t  Hello World!   "
print(text.lstrip())
Enter fullscreen mode Exit fullscreen mode

Output:
Hello World!

Rstrip():

text = "Hello World \n \t"
print(f"'{text.rstrip()}'")
Enter fullscreen mode Exit fullscreen mode

Output:
'Hello World'

Isspace():

space = '   '
print(space.isspace())
Enter fullscreen mode Exit fullscreen mode

Output:
True

Isalnum():

alnum = 'hi5'
print(alnum.isalnum())
Enter fullscreen mode Exit fullscreen mode

Output:
True

Isnumeric:

num = '½'
print(num.isnumeric())
Enter fullscreen mode Exit fullscreen mode

Output:
True

Isdigit():

num = '49'
print(num.isdigit())
Enter fullscreen mode Exit fullscreen mode

Output:
True

Format():

print('{0}, {1}, {2}'.format('a', 'b', 'c'))
print('{}, {}, {}'.format('a', 'b', 'c'))  
print('{2}, {1}, {0}'.format('a', 'b', 'c'))
print('{2}, {1}, {0}'.format(*'abc'))    
print('{0}{1}{0}'.format('abra', 'cad'))   
Enter fullscreen mode Exit fullscreen mode

Output:
a, b, c
a, b, c
c, b, a
c, b, a
abracadabra

Top comments (0)