Python Strings Tutorial

In Python strings are immutable, basically after creating a string you cannot alter them. You can use slicing to create new string from old strings but you cannot do assignments to an existing string. In this tutorial we will review the most common uses of Strings.

How to create a String

You can either use a single quote or a double quote to create a string.
>>> myWebsite = "http://www.mysamplecode.com"
>>> myWebsite
'http://www.mysamplecode.com'

How to use a single quote inside a String

You can either use double quotes around them or use the backslash (\) escape character. Using the backslash is better idea as the string itself may contain double quotes also.
>>> myString = "Let's learn Python, it's easy."
>>> myString
"Let's learn Python, it's easy."
>>> myString = 'Let\'s learn Python, it\'s easy.'
>>> myString
"Let's learn Python, it's easy."

How to use a double quotes inside a String

You can either use single quotes around them or use the backslash (\) escape character. Using the backslash is better idea as the string itself may contain double quotes also.
>>> myString = 'This dimensions of this table are 6" x 4"'
>>> myString
'This dimensions of this table are 6" x 4"'
>>> myString = "This dimensions of this table are 6\" x 4\""
>>> myString
'This dimensions of this table are 6" x 4"'

How to write a long String

You have to use the backslash as a line continuation escape character.
>>> myString = "This dimensions of this \
table are 6\" x 4\""
>>> myString
'This dimensions of this table are 6" x 4"'
If you want to write a really long String, you can use triple quotes instead of ordinary quotes. You can also use triple double quotes. Both single and double quotes are allowed inside, without being backslash escaped.
>>> myLongString = '''This is a very long String.
Second line in the String.
Third line in the String.
Let's learn Python. It's easy.
Enough! Let's end this.'''
>>> myLongString
"This is a very long String.\nSecond line in the String.\nThird line in the String.\nLet's learn Python. It's easy.\nEnough! Let's end this."
>>> print(myLongString)
This is a very long String.
Second line in the String.
Third line in the String.
Let's learn Python. It's easy.
Enough! Let's end this.

String in Python is immutable

>>> myString = 'Let\'s learn Python, it\'s easy.'
>>> myString[3:] = "Let's change the string"

Traceback (most recent call last):
  File "", line 1, in 
    myString[3:] = "Let's change the string"
TypeError: 'str' object does not support item assignment

How to do substring/slicing

Index starts from 0 on the left side and -1 from the right side.
>>> myWebsite = "http://www.mysamplecode.com"
>>> myString = myWebsite[7:]
>>> myString
'www.mysamplecode.com'
>>> myString = myWebsite[7:23]
>>> myString
'www.mysamplecode'
>>> myString = myWebsite[-3:]
>>> myString
'com'
>>> myString = myWebsite[-20:-4]
>>> myString
'www.mysamplecode'

How to find the length of a String

>>> myTemplate = '''
<html>
<head><title>{}</title></head>
<body>
{}
</body>
</html>'''
>>> myString = myTemplate.format('Python Tutorial','<h1>Python String manipulation</h1>')
>>> myString
'\n<html>\n<head><title>Python Tutorial</title></head>\n<body>\n<h1>Python String manipulation</h1>\n</body>\n</html>'
>>> print(myString)

<html>
<head><title>Python Tutorial</title></head>
<body>
<h1>Python String manipulation</h1>
</body>
</html>

>>> myTemplate = "What are the key differences between {0} and {1}?"
>>> myValues = ('Python','Java')
>>> myString = myTemplate.format(*myValues)
>>> myString
'What are the key differences between Python and Java?'

>>> myTemplate = "What are the key differences between {1} and {1}?"
>>> myString = myTemplate.format('Python','Java')
>>> myString
'What are the key differences between Java and Java?'

>>> myTemplate = "What are the key differences between {one} and {two}?"
>>> myString = myTemplate.format(two='Python',one='Java')
>>> myString
'What are the key differences between Java and Python?'

How to format real numbers and display as String

>>> myValue1 = 12.1234567
>>> myValue2 = -34.1234567
>>> '{:+f}; {:+f}'.format(myValue1, myValue2)
'+12.123457; -34.123457'
>>> '{:f}; {:f}'.format(myValue1, myValue2)
'12.123457; -34.123457'
>>> '{:.2f}; {:.5f}'.format(myValue1, myValue2)
'12.12; -34.12346'
>>> '{:10.2f}; {:5.5f}'.format(myValue1, myValue2)
'     12.12; -34.12346'
>>> 'Divide: {:.2%}'.format(myValue1/myValue2)
'Divide: -35.53%'

How to TimeStamp and display as String

>>> import datetime
>>> myDate = datetime.datetime(2012, 10, 13, 12, 15, 35)
>>> myStringDate = '{:%Y-%m-%d %H:%M:%S}'.format(myDate)
>>> myStringDate
'2012-10-13 12:15:35'

How to do String substitution using keywords

Sring substitution work more like replacement variables. For substitution to work you have to first create a Template. Here is how
>>> from string import Template
>>> myTemplate = Template('What are the key differences between ${one} and ${two}?')
>>> myString = myTemplate.substitute(one='Java',two='Python')
>>> myString
'What are the key differences between Java and Python?'

How to do String substitution using dictionary

>>> from string import Template
>>> myString = myTemplate.substitute(one='Java',two='Python')
>>> dict = {}
>>> dict['one'] = 'Java'
>>> dict['two'] = 'Python'
>>> dict
{'two': 'Python', 'one': 'Java'}
>>> myString = myTemplate.substitute(dict)
>>> myString
'What are the key differences between Java and Python?'

How to find a substring within a larger String

The find() method it returns the leftmost index where the substring is found. If it is not found, –1 is returned.
>>> myString = 'What are the key differences between Java and Python?'
>>> myString.find('Java')
37
>>> myString.find('java')
-1
How to specify the range when doing the find operation
>>> myString.find('Java',0,25)
-1
>>> myString.find('Java',25,len(myString))
37

How to join entries in a List to create a String

>>> myList = ['Java','C','Python','HTML','XML','JavaScript']
>>> myString = ' '.join(myList)
>>> myString
'Java C Python HTML XML JavaScript'
>>> myString = ', '.join(myList)
>>> myString
'Java, C, Python, HTML, XML, JavaScript'

Please note: You cannot join a list of numbers they must be String!
>>> myList = [100,101,102,103,104]
>>> myString = ' '.join(myList)

Traceback (most recent call last):
  File "", line 1, in 
    myString = ' '.join(myList)
TypeError: sequence item 0: expected string, int found

How to split a String using a separator and create a List

If don't specify a separator then it looks for spaces in between.
>>> myString = 'Java, C, Python, HTML, XML, JavaScript'
>>> myList = myString.split(',')
>>> myList
['Java', ' C', ' Python', ' HTML', ' XML', ' JavaScript']
>>> myList = myString.split()
>>> myList
['Java,', 'C,', 'Python,', 'HTML,', 'XML,', 'JavaScript']
>>> myList = myString.split(', ')
>>> myList
['Java', 'C', 'Python', 'HTML', 'XML', 'JavaScript']

How to convert a string to lowercase and uppercase

>>> myString = 'What are the key differences between Java and Python?'
>>> myString.lower()
'what are the key differences between java and python?'
>>> myString.upper()
'WHAT ARE THE KEY DIFFERENCES BETWEEN JAVA AND PYTHON?'

How to do find and replace

The replace method replaces all the occurrences of the given String with the new String if you don't specify the number of occurences to replace.
>>> myString = 'Python is easy to learn. How to manipulate Strings in Python?'
>>> myString.replace('Python','Java')
'Java is easy to learn. How to manipulate Strings in Java?'
>>> myString = 'Python is easy to learn. How to manipulate Strings in Python?'
>>> myString.replace('Python','Java',1)
'Java is easy to learn. How to manipulate Strings in Python?'

How to trim blanks from a String

>>> myString = '   Python is easy to learn.    '
>>> myString.strip()
'Python is easy to learn.'
>>> myString = '   Python is easy to learn.    '
>>> myString.lstrip()
'Python is easy to learn.    '
>>> myString = '   Python is easy to learn.    '
>>> myString.rstrip()
'   Python is easy to learn.'
You can even strip out characters from a String.
>>> myString = '$? Python is easy to learn  $  ?'
>>> myString.strip(' $?')
'Python is easy to learn'

How to use translation table for character by character replacement

>>> myString = 'python is easy to learn.'
>>> myTable = maketrans('python','PYTHON')
>>> len(myTable)
256
>>> myTable[97:123]
'abcdefgHijklmNOPqrsTuvwxYz'
>>> myString.translate(myTable)
'PYTHON is easY TO learN.'

How to convert a String to an Integer

>>> myString = '1234'
>>> int(myString)
1234

How to convert a Tuple of Strings to an Integer List

>>> myString = ('101','102','103','104','105')
>>> myList = map(int, myString)
>>> myList
[101, 102, 103, 104, 105]

How to convert a String to Float

>>> myString = "123.12"
>>> float(myString)
123.12

How to convert a String to Date

>>> from datetime import datetime
>>> myString = "2012-10-13"
>>> datetime.strptime(myString,'%Y-%m-%d')
datetime.datetime(2012, 10, 13, 0, 0)
>>> myString = '2012-10-13 12:15:35'
>>> datetime.strptime(myString,'%Y-%m-%d %H:%M:%S')
datetime.datetime(2012, 10, 13, 12, 15, 35)

How to convert a String to an equation

>>> myString = '(1+2) * (3+4)'
>>> myResult = eval(myString)
>>> myResult
21

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.