Another 5 Helpful Python String Methods

Hello, I'm Aya Bouchiha,

this is the part 2 of 5 useful python string methods.

capitalize()

capitalize(): this string method converts to uppercase the first letter of the first word in the specified string.

first_name = "aya"

print(first_name.capitalize()) # Aya

isalpha()

isalpha(): checks if all string's characters are alphabets letters [A-z].

print('AyaBouchiha'.isalpha())   # True
print('Aya Bouchiha'.isalpha())  # False
print('Aya-Bouchiha'.isalpha())  # False
print('AyaBouchiha 1'.isalpha()) # False
print('Aya Bouchiha!'.isalpha()) # False

isdigit()

isdigit(): checks if all string's characters are digits.

print('100'.isdigit())     # True
print('12a'.isdigit())     # False
print('100 000'.isdigit()) # False
print('+212-6000-00000'.isdigit()) # False
print('12a'.isdigit()) # False

print('3\u00B2') # 3²
print('3\u00B2'.isdigit()) # True

isalnum()

isalnum(): checks if all string's characters are alphanumeric (alphabets, numbers).

print('2021'.isalnum()) # True
print('30kviews'.isalnum()) # True
print('+212600000000'.isalnum()) # False           
print('dev.to'.isalnum()) # False  
print('[email protected]'.isalnum()) # False   
print('Aya Bouchiha'.isalnum()) # False

strip()

strip(characters(optional)): lets you delete the given characters (by default => whitespaces) at the start and at the end of the specified string.

print(' Aya Bouchiha  '.strip()) # Aya Bouchiha
print('   +212612345678  '.strip(' +')) # 212612345678
print('Hi, I\'m Aya Bouchiha'.strip('Hi, ')) # I'm Aya Bouchiha

Summary

  • capitalize(): converts to uppercase the first letter of the first word in the specified string.
  • isalpha(): checks if all string's characters are alphabets letters.
  • isdigit(): checks if all string's characters are digits.
  • isalnum(): checks if all string's characters are alphanumeric.
  • strip(): deletes the given characters (by default => whitespaces) at the start and at the end of the specified string.

Suggested Posts

To Contact Me:

telegram: Aya Bouchiha

Have a great day!

22