Learn Python Tutorial - Strings


Python Basics

(Learn Python Programming in 20 Minutes)



3 Python commands



3.9 Strings 

A string in Python is a sequence of characters. In some sense strings are similar to lists, however, there are important differences. One major difference is that Python strings are immutable, meaning that we are not allowed to change individual parts of them as we could for a list. So if x is an existing string, then x[i] gets the character at position i, but we are not allowed to reassign that character, as in x[5] = ’s’.
>>> x = ’gobbletygook’ 
>>> x[2] 
’b’ 
>>> x[5] 
’e’ 
>>> x[5] = ’s’ 
Traceback (most recent call last): 
    File "<stdin >", line 1, in <module> 
TypeError: ’str’ object does not support item assignment

Just as for lists, string items are indexed starting at 0. Slicing for strings works exactly the same as for lists. The length function len is the same as for lists, and concatenation is the same too. But the list methods append, insert, delete, and pop are not available for strings, because strings are immutable. If you need to change an existing string, you must make a new, changed, one. There are many string methods for manipulating strings, documented in the Python Library Reference Manual [2]. For example, you can capitalize an existing string x using x.capitalize(); this returns a new copy of the string in which the first character has been capitalized.

>>> a = ’gobbletygook is refreshing’ 
>>> a.capitalize()
’Gobbletygook is refreshing’

Other useful methods are find and index, which are used to find the first occurence of a substring in a given string. See the manuals for details.



References

[1] Guido van Rossum, Python Tutorial, http://docs.python.org.
[2] Guido van Rossum, Python Library Reference Manual,
http://docs.python.org. 

 


No comments:

Post a Comment

Your feedback is highly appreciated and will help us to improve our content.