Udacity CS 101: Strings

Strings are basically a sequence of characters (a ,b ,c d …). Strings in Python are denoted by quotes.

Colourful Strings

Image courtesy of dreamstimes

'Hello Everyone' # this is a valid string, single quotes work

"Hello Everybody" # this is a valid string too, double quotes work too

"Hello I'm Zhi An" # this is valid too, the end of a string initiated by double quotes will end with double quotes, hence the single quote in the middle is recognized and printed

Strings are basically what we will be working with in the search engine we are building, links to websites are basically just a long string, for example, https://ngzhian.wordpress.com is basically a string made up of the characters h, t, t, p, :, /, / etc…

Professor Evans made a quite mention on the convention of naming a variable while assigning the string "Howdy" to the variable hello. Conventions are basically good practices that programmers adopt to increase the efficiency and readability of codes. The convention on variable naming is that variable names begin with a small letter, so instead of Hello, it is better typed as hello

Strings can be concatenated, or tied together, using the + (plus) operator.

Just like how print 1 + 1 will show you 2

print "hi" + "there" will show you hithere

Notice the absence of a space between the words hi and there. By default, + will join two strings together without placing a space in between, and if you wish to add a space in between to maintain the meaning of the phrase, you would have to do it manually:

Either by adding a space after hi: 'hi '

Or by adding a space before there: ' there'

If you ever attempt to do this: print "hi" + 10  you will get a syntax error. So no, you cannot concatenate strings and numbers. However if your intention is to to print the something your age

My age is 10

A work around will be

print "My age is " + "10"

In this case the program will run because the number 10 is quoted, hence it is recognized as a string, containing the characters 1 and 0, by Python. The output will be the same as above.

Strangely, multiplication works.

print "HELLO!" * 5 # will give you the output

HELLO!HELLO!HELLO!HELLO!HELLO!

You probably wouldn’t use this much unless you wish to print multiple smileys:

print ":)" * 50

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s