Strings in Python

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. This contrasts with most other scripting languages, which use single quotes for literal strings and double quotes to allow escaping of characters. Python uses the “raw string” operator to create literal quotes, so no differentiation is necessary. Other languages such as C use single quotes for characters and double quotes for strings. Python does not have a character type; this is probably another reason why single and double quotes are the same.
Nearly every Python application uses strings in one form or another. Strings are a literal or scalar type, meaning they are treated by the interpreter as a singular value and are not containers which hold other Python objects. Strings are immutable, meaning that changing an element of a string requires creating a new string. Strings are made up of individual characters, and such elements of strings may be accessed sequentially via slicing.

How to Create and Assign Strings

>>> aString = 'hello world'
>>> anotherString = "Hello world"
>>> aString
'hello world'
>>> anotherString
'Hello world'
>>> aBlankString = ''
>>> print aBlankString

Python does not support a character type; these are treated as strings of length one, thus also considered a substring. To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring:

>>> aString = 'Hello world'
>>> aString[0]
>>> aString[1:5]
>>> aString[6:]

How to Update Strings

>>> aString = aString[:6] + 'Python'
>>> aString
'Hello Python'
>>> aString = 'different string altogether'
>>> aString
'different string altogether'

How to Remove Characters and Strings

>>> aString = "new world"
>>> aString = ""
>>> aString
>>> del (aString)
>>> aString

Traceback (most recent call last):
  File "<pyshell#104>", line 1, in <module>
NameError: name 'aString' is not defined

You may also like...