how to creating strings of characters in python
From email readers and web browsers to calendars and games, text plays a
central role in computer programs. This chapter introduces a non-numeric data
type that represents text, such as the words in this sentence or the sequence
of bases in a strand of DNA. Along the way, we will see how to make programs a
little more interactive by printing messages to our programs users and getting
input from them.
Creating Strings of Characters :
Computers may have been invented to do arithmetic, but these days, most
of them spend a lot of their time processing text. Many programs create text,
store it, search it, and move it from one place to another. In Python, text is represented as a string, which is a sequence of characters (letters, digits, and symbols). The type whose values are sequences of characters is str. The characters consist of those from the Latin alphabet found on most North American keyboards, as well as Chinese morphograms, chemical symbols, musical symbols, and wuch nore. In Python, we indicate that a value is a string by putting either single or double quotes around it. As we will see in Section 4.2, Using Special Characters in Strings, on page 68, single and double quotes are equivalent except for strings that contain quotes. You can use whichever you prefer. (For docstrings, the Python style guidelines say that double quotes are preferred.)
Here are two examples:
>>>
'Aristotle' 'Aristotle' >>> "Isaac Newton" 'Isaac Newton
The opening and
closing quotes must match:
Working with Text * 66
>>> 'Charles
Darwin" File "<stdin>", line 1
Charles Darwin"
syntax error: EOL
while scanning string literal
error above indicates
that the end of the EOL stands for "end of the line." The error above
indicates that line was reached before the end of the string (which should be
marked with a closing single quote) was found.
acters limited only
by computer memory.
Strings can contain
any number of characters, limited only by computer The shortest string is the
an empty string, containing no characters at a
Operations on Strings
Python
has a built-in function, len, that returns the number of characters between the
opening and closing quotes: >>> len ('Albert Einstein') 15
>>> len('123')
>>> len(' ')
>>> len('')
We can add two
strings using the + operator, which produces a new string containing the same
characters as in the two operands:
>>> 'Albert'
+ ' Einstein' 'Albert Einstein'
When + has two string
operands, it is referred to as the concatenation operator. Operator + is
probably the most overloaded operator in Python. So far, we've applied it to
integers, floating-point numbers, and strings, and we'll apply it to several
more types in later chapters.
As the following
example shows, adding an empty string to another string produces a new string
that is just like the nonempty operand:
>>>
"Alan Turing" + " 'Alan Turing' >>>" + 'Grace
Hopper' 'Grace Hopper
report erratum. discus
No comments:
Post a Comment