In this post, we will see how to manage a string in Python.
SLICING
person = "Damiano Abballe"
print(person[0:5]) # => Damia
print(person[3:6]) # => ian
print(person[::2]) # => DmaoAble
print(person[::-1]) # => ellabbA onaimaD
FROM STRING TO LIST AND VICE VERSA
inputstring = "one;two;three;four;five"
inputList = inputstring.split(';')
print(type(inputstring))
print(inputstring)
print(type(inputList))
print(inputList)
inputList = ["one","two","three", "four", "five"]
inputstring = '/'.join(inputList)
print(type(inputList))
print(inputList)
print(type(inputstring))
print(inputstring)
COUNT AND FIND
inputString = "Damiano Abballe "
# count characters
print(len(inputString)) # => 16
# delete the blanks
print(len(inputString.strip())) # => 15
# count how many characters are in the string
print(inputString.count('a')) # => 3
print(inputString.lower().count('a')) # => 4
# find the first specific character in the string
print(inputString.find('D')) # => 0
print(inputString.find('a')) # => 1
print(inputString.find('l')) # => 12
LJUST, RJUST, STRIP, LSTRP AND RSTRIP
stringValue = "Damiano"
print(stringValue)
'''
Using ljust we will add at our string n characters until to arrive at the value declared, adding the character specified (in this case '@').
The new string will be left-aligned.
'''
print(stringValue.ljust(20, '@')) # Result => Damiano@@@@@@@@@@@@@
'''
With rjust we will have the same result but the new string will be right-aligned.
'''
print(stringValue.rjust(20, '@')) # Result => @@@@@@@@@@@@@Damiano
stringValue2 = " Damiano "
'''
Using strip, we will delete all empty spaces on the right and on the left.
'''
print(f"{stringValue2} - length: {len(stringValue2)}") # Result => ' Damiano ' - length: 11
print(f"{stringValue2.strip()} - length: {len(stringValue2.strip())}") # Result => 'Damiano' - length: 7
'''
Using lstrip, we will delete all empty spaces on the left.
'''
print(f"{stringValue2} - length: {len(stringValue2)}") # Result => ' Damiano ' - length: 11
print(f"{stringValue2.lstrip()} - length: {len(stringValue2.lstrip())}") # Result => 'Damiano ' - length: 9
'''
Using rstrip, we will delete all empty spaces on the right.
'''
print(f"{stringValue2} - length: {len(stringValue2)}") # Result => ' Damiano ' - length: 11
print(f"{stringValue2.rstrip()} - length: {len(stringValue2.rstrip())}") # Result => ' Damiano' - length: 9