Before, we added and multiplied strings, and I mentioned there's other ways to change strings. Here's a few of them:
Can you guess what
print "Well hello there" does?
In the console, it doesn't look like it does much that's new or novel. That's because the console always prints out the result of whatever we type into it.
You can better see what the
Running the code should have produced one
Well hello there! line. Notice there aren't double quotes (
"") weren't printed; it's just the words inside them.
The second line of code we wrote –
print "Well hello there!" produced the
Well hello there! you saw printed. The first line of code didn't print anything.
If you don't believe me, try deleting the first line and re-running the code. (The same thing will print as before.) Then, put it back in, delete the second line, and re-run the code: nothing will print!
What do you think
len("Measure me") does?
Wrapping a string with
len( ... ) returns the length of the string. You can put whichever string you like in the parentheses.
Just make sure the thing in the parentheses is a string; Python doesn't know how to find, say, the
How about this code:
"Today we're playing around with strings in Python".split()?
.split() after a string cuts the string into pieces and uses whitespace (
" ") as the splitter.
.upper() after any string returns that same string, but in uppercase letters. It doesn't "uppercase" punctuation or numbers though – just letters.
What do you think
"Change me!".lower() does?
.lower() after a string converts all its letters into lowercase ones. Same deal here:
.lower() works only on letters and leaves numbers and symbols (like "!") unchanged.
What do you think this code does?
"change me! no really!".capitalize()
.capitalize() after a string capitalizes the first letter of the string and lowercases all the others. It doesn't try to capitalize the first letter of subsequent sentences – only the first sentence gets capitalization treatment.
Print your name in the console using the
Take a look at the following lines of code. Take a guess as to what they do, then try them out in the console below.
len("Hi there") len("Hi") == len("hi") len("hello") > 5
Take a look at the following lines of code. Guess what they'll do when run, then try them out in the console below.
"a ball".split() "ball".split() "a ball is very high".split() "".split()
What about these lines of code?
"hello".upper() "HELLO".upper() "Hi!".upper() "hI!".upper()
"hello".lower() "HELLO".lower() "Hi!".lower() "hI!".lower()
Last ones: what about these?
"hello".capitalize() "HELLO".capitalize() "Hi!".capitalize() "hI!".capitalize()