0% found this document useful (0 votes)
20 views

String Function

The document discusses various string methods in Python like slicing, stripping, replacing, splitting, joining, checking cases, finding indices and modifying cases.

Uploaded by

pragyarani78700
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

String Function

The document discusses various string methods in Python like slicing, stripping, replacing, splitting, joining, checking cases, finding indices and modifying cases.

Uploaded by

pragyarani78700
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

STRING FUNCTION

Slicing
With slicing we can access substrings. It can get optional start and stop indices.
s = ' hello '
s = s[3:8] # no crash if s[3:20]
# 'hello'

strip()
Return a copy of the string with the leading and trailing characters removed. The
chars argument is a string specifying the set of characters to be removed. If omitted
or None, the chars argument defaults to removing whitespace.
s = ' hello '.strip()
# 'hello'

lstrip() and rstrip()


lstrip([chars]): Return a copy of the string with leading characters removed.
rtrip([chars]): Return a copy of the string with trailing characters removed.

s = ' hello '.lstrip()


# 'hello '

s = ' hello '.rstrip()


# ' hello'

strip() with character


We can specify character(s) instead of removing the default whitespace.
s = '###hello###'.strip('#')
# 'hello'

Careful: only leading and trailing found matches are removed:


s = ' \n \t hello\n'.strip('\n')
# -> not leading, so the first \n is not removed!
# ' \n \t hello'

s = '\n\n \t hello\n'.strip('\n')
# ' \t hello'
strip() with combination of characters

The chars argument is a string specifying the set of characters to be removed. So


all occurrences of these characters are removed, and not the particular given string.
s = 'www.example.com'.strip('cmow.')
# 'example'

removeprefix() and removesuffix()


Like seen before, strip, lstrip, and rstrip remove all occurrences of the passed chars
string. So if we just want to remove the given string, we can use remove prefix and
removesuffix.
s = 'Arthur: three!'.lstrip('Arthur: ')
# 'ee!'

s = 'Arthur: three!'.removeprefix('Arthur: ')


# 'three!'

s = 'HelloPython'.removesuffix('Python')
# 'Hello'

replace()
Return a copy of the string with all occurrences of substring old replaced by new.
s = ' \n \t hello\n'.replace('\n', '')
# ' \t hello'
8. re.sub()
If we want to replace a specific pattern with another character, we can use
the re module and use a regular expression.
import re
s = "string methods in python"
s2 = re.sub("\s+" , "-", s)
# 'string-methods-in-python'

split()
Return a list of the words in the string, using sep as the delimiter string. If maxsplit
is given, at most maxsplit splits are done.
s = 'string methods in python'.split()
# ['string', 'methods', 'in', 'python']

s = 'string methods in python'.split(' ', maxsplit=1)


# ['string', 'methods in python']
rsplit()
Return a list of the words in the string, using sep as the delimiter string. If maxsplit
is given, at most maxsplit splits are done, the rightmost ones.
s = 'string methods in python'.rsplit()
# ['string', 'methods', 'in', 'python']

s = 'string methods in python'.rsplit(' ', maxsplit=1)


# ['string methods in', 'python']

join()
Return a string which is the concatenation of the strings in iterable.
list_of_strings = ['string', 'methods', 'in', 'python']
s = ' '.join(list_of_strings)
# 'string methods in python'

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.
s = 'python is awesome!'.upper()
# 'PYTHON IS AWESOME!'

s = 'PYTHON IS AWESOME!'.lower()
# 'python is awesome!'

s = 'python is awesome!'.capitalize()
# 'Python is awesome!'

islower(), isupper()
Checks if the string consist only of upper or lower characters.
'PYTHON IS AWESOME!'.islower() # False
'python is awesome!'.islower() # True

'PYTHON IS AWESOME!'.isupper() # True


'PYTHON IS awesome!'.isupper() # False

isalpha(), isnumeric(), isalnum()


isalpha(): Return True if all characters in the string are alphabetic and there is at
least one character, False otherwise.
isnumeric(): Return True if all characters in the string are numeric characters, and
there is at least one character, False otherwise.

isalnum(): Return True if all characters in the string are alphanumeric and there is
at least one character, False otherwise.
s = 'python'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# True False True

s = '123'print(s.isalpha(), s.isnumeric(), s.isalnum() )


# False True True

s = 'python123'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# False False True

s = 'python-123'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# False False False
count()
Return the number of non-overlapping occurrences of substring sub in the range
[start, end].
n = 'hello world'.count('o')

find()
Return the lowest index in the string where substring sub is found within the slice
s[start:end].
s = 'Machine Learning'
idx = s.find('a')
print(idx) # 1
print(s[idx:]) # 'achine Learning'

idx = s.find('a', 2)
print(idx) # 10
print(s[idx:]) # 'arning'
rfind()
Return the highest index in the string where substring sub is found, such that sub is
contained within s[start:end].
s = 'Machine Learning'
idx = s.rfind('a')
print(idx) #

startswith() and endswith()


Return True if string starts/ends with the prefix/suffix, otherwise return False.
s = 'Patrick'.startswith('Pat') # case sensitive!
# True

s = 'Patrick'.endswith('k') # case sensitive!


# True
partition()
Split the string at the first occurrence of sep, and return a 3-tuple containing the
part before the separator, the separator itself, and the part after the separator. If the
separator is not found, return a 3-tuple containing the string itself, followed by two
empty strings.
s = 'Python is awesome!'
parts = s.partition('is')
# ('Python ', 'is', ' awesome!')

parts = s.partition('was')
# ('Python is awesome!', '', '')

center(), ljust(), rjust()


center(): Return centered in a string of length width. Padding is done using the
specified fillchar (default is a space).

ljust(): Return the string left justified in a string of length width. Padding is done
using the specified fillchar (default is a space).

rjust(): Return the string right justified in a string of length width. Padding is done
using the specified fillchar (default is a space).
s = 'Python is awesome!'
s = s.center(30, '-')
# ------Python is awesome!------

s = 'Python is awesome!'
s = s.ljust(30, '-')
# Python is awesome!------------

s = 'Python is awesome!'
s = s.rjust(30, '-')
# ------------Python is awesome!

f-Strings
Since Python 3.6, f-strings can be used to format strings. They are more readable,
more concise, and also faster!
num = 1
language = 'Python'
s = f'{language} is the number {num} in programming!'
# 'Python is the number 1 in programming!'
30. swapcase()
Return a copy of the string with uppercase characters converted to lowercase and
vice versa.
s = 'HELLO world'
s = s.swapcase()
# 'hello WORLD'

zfill()
Return a copy of the string left filled with ‚0‘ digits to make a string of length
width. A leading sign prefix (‚+‘/'-') is handled by inserting the padding after the
sign character rather than before.
s = '42'.zfill(5)
# '00042'

s = '-42'.zfill(5)
# '-0042'

You might also like