DEV Community

shiva yada
shiva yada

Posted on

String Methods (python)

String Methods

  • Slicing

With slicing we can access substrings. It can get optional start and stop indices.

a='pythonfullstack'
a= a[3:9]
# 'honful'
Enter fullscreen mode Exit fullscreen mode
  • strip()

strip() method makes the string Return a copy of the string with the leading and trailing characters removed. default characters of this method removes whitespace

a= '      python    '
a= a.strip()
#'python'
Enter fullscreen mode Exit fullscreen mode
  • replace() Return a copy of the string with all occurrences of substring old replaced by new.
a= ' hi folks'
a= a.replace('hi','hello')
# ' hello folks'
Enter fullscreen mode Exit fullscreen mode
  • split() split() methods uses for returning the list of words in a string, using sep as the delimiter string
a= ' hi folks good morning'
a= a.split()
# ['hi', 'folks', 'good' ,'morning']
Enter fullscreen mode Exit fullscreen mode
  • join() Return a string which is the concatenation of the strings in iterable.
a=['hi', 'folks', 'good' ,'morning']
a= ' '.join(a)
# 'hi folks good morning'
Enter fullscreen mode Exit fullscreen mode
  • upper(), lower(), capitalize() Return a copy of the string with all the cased characters converted to uppercase, lowercase, or first character capitalized and the rest lowercased.
a= 'python'
a= a.upper()
#'PYTHON'
a='pyThOn'
a= a.lower()
# 'python'
a= 'pyTHoN'
a=a.capitalize()
# 'Python'
Enter fullscreen mode Exit fullscreen mode
  • isalpha(), isnumeric(), isalnum()

isalpha() is to check a string whether it contains alphabets only.

isnumeric() is to check a string whether it contains numbers only.

isalnum() is to check a string whether it contains alphabets or numbers.

s= 'justchill'
s.isalpha() #output : True
s='9887'
s.isnumeric() # output: True
s='30jno'
s.isalnum() #output: True
Enter fullscreen mode Exit fullscreen mode
  • count() count() method is used to count the particular substrings in a string.
s='hello'
s.count('l') # 2
Enter fullscreen mode Exit fullscreen mode
  • find() Return the lowest index in the string where substring sub is found within the slice s[start:end]
s= 'run python'
ind= s.find('y') # 5

Enter fullscreen mode Exit fullscreen mode
  • swapcase()

Return a copy of the string with uppercase characters converted to lowercase and vice versa.

s= 'HeLLo'
s=s.swapcase()
# 'hEllO'

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay