DEV Community

Vicki Langer
Vicki Langer

Posted on • Updated on

Charming the Python: Strings

If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.


Strings

Creating a string

Strings are a bunch of characters within quotes.

'7his is a string'

"Th15 is also a string!"

"""This is a 
multi-line 
string."""

'This is a "quote" inside of a string.'

"This is also 'quote' inside of a string"
Enter fullscreen mode Exit fullscreen mode

String Concatenation

Concatenation is a long word that means you're putting things together.

first_name = "Vicki"
last_name = 'Langer'

full_name = first_name + " " + last_name

print(full_name)
>>>Vicki Langer
Enter fullscreen mode Exit fullscreen mode

Escape Sequences in string

Sequence What it does
\n new line
\t tab or 8 spaces
\ backslash
\' single quote
\" double quote
print('Are you enjoying my python notes.\nLet me know in the comments')
>>>Are you enjoying my python notes.
>>>Let me know in the comments
Enter fullscreen mode Exit fullscreen mode

String formating

string formating is a great way to template things

name = 'Vicki'
language = 'Python'
formatted_string = "Hi, I'm {}. I am writing about {}".format(name, language)
print(formatted_string)
>>>Hi, I'm Vicki. I am writing about Python
Enter fullscreen mode Exit fullscreen mode
# this is called "f-string"
name = 'Vicki'
language = 'Python'
formatted_string = f"Hi, I'm {name}. I am writing about {language}"
Enter fullscreen mode Exit fullscreen mode

Accessing characters in strings by index

the first character in the string is considered 0
You may also get the last charater by referring to -1

p y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
language = 'python'

first_letter = language[0]
print(first_letter)
>>> p

last_letter = language[-1]
print(last_letter)
>>> n
Enter fullscreen mode Exit fullscreen mode

Slicing Python Strings


first_three = language[0,3] # starts at zero index and up to but not including index 3
>>>pyt
>
last_three = language[3:6]
>>>hon
Enter fullscreen mode Exit fullscreen mode

Reversing a string

greeting = 'Hello, World!'
print(greeting[::-1]) 
>>>!dlroW ,olleH
Enter fullscreen mode Exit fullscreen mode

Skipping characters while slicing

language = 'the next line is telling us we want to look at the characters between 0 index and 100 index, then it is only going to give us ever 2nd number'
every_other = language[0,100:2]
Enter fullscreen mode Exit fullscreen mode

Series based on

Top comments (0)