3.3. Strings - JulTob/Python GitHub Wiki
Characters are single letters or symbols inside the computer's knowledge.
We can check the codification of a character with the function ord
ord('a')
bin(ord('a')) # To check the binary representation
And decode with the function chr
chr(97)
"Strings are what we call long strings of character on quotation marks"
'So... "Text"'
'strings can go on \
to the next line.'
'''It can expand some lines.
And contain special characters'''
"""Triple quotes can also work as comments, btw.
Just saying"""
r"Raw strings can show characters such as \n [new line]."
text = 'wasssap'
print(text)
π¦ Casting transforms a diferent type into a string of text.
str() #Cast
π’ To insert variable text into a string.
name = "Jon"
surname = "Snow"
print("Hello {}".format(name) )
print("You know nothing {} {}".format(name,surname) )
title = "King of The North"
print(f"{name} {surname}, {title}")
surname = "Stark"
title = title.replace("of The North","Beyond the Wall")
print(f"{name} {surname}, {title}")
# Remove Whitespace
text = " Avada Kedabra \n".strip()
# "Avada Kedabra"
text = 'Romeo and Juliet'
text = str.lower(text)
text.title() # Romeo And Juliet
text.upper() # ROMEO AND JULIET
text.lower() # romeo and juliet
text.capitalize() # Romeo and juliet
text.swapcase() # rOMEO AND jULIET
test = "What?"
text.find('Wh') # 0
text.isaplpha() # True
text.isalnum() # True
text.isupper() # Is all uppercases?
text.islower() # Is all lowercase?
text.replace('wa', 'Wo')
text.strip(" ") # Whitspaces off, also by default
text.lstrip("$") # Left stripe off
text.rstrip(".") # Right side stripe off
text.split() # list of words
multiplication= "Na β * 3 # Na Na Na # Repeat
Text = βsomeβ + β β + βwordsβ + β β + βconcatenateβ
Text = βsomeβ β β βliteralsβ β β βconcatenateβ βautomaticallyβ β.β
my_name = βTony Starkβ
first_char = my_name[0]
last_char = my_name[-1]
slice = my_name[:2] # βTonβ
slice = my_name[1:2] # βonβ
sart_stop_step= my_name[1:-1:2] # βoySaβ
name[0] : First letter
name[<0..(length-1)>] : That letter
name[β<0..(length-1)>] : Character from last
name[-1]=last
name[0:3]= name[0]+name[1]+name[2]
name[ :3]= name[0]+name[1]+name[2]
name[3: ]= name[3]+...
name[:]= name
letter_index = my_name.index("o") # First index
letter_count = my_name.count("o")
bool_contains = "a" in my_name
bool_slice_not_in = "Tony" not in my_name
length_of_string = len(my_name) # 10
other_name = my_name.replace('Tony', 'Ned')
palindrome = reversed('Ana')
palindrome = palindrome [::-1]
counting = β{0}, {1}, and {2}β.format(βZeroβ, βOneβ, βTwoβ)
hal = βHello {name}, I {feel} you.β.format( name = βdaveβ, feel = βfriendzoneβ)
French_Lesson = β{}, et {}β.format(βOh la laβ, βMon dieuβ)
β-β.join(βaβ,βbβ,βcβ) # a-b-c
βBreak me, againβ.split() # ['Break', 'me,', 'again']
βBreak me, againβ.split(",") # ['Break me', ' again']
counting = '{0}, {1}, and {2}'.format(βZeroβ, βOneβ, βTwoβ)
"Hello, %s , From My Function!, I wish you %s"%(username, greeting)
# C string style
# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))
# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)
%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)
Escape = ' scape \' the string rules'
Quote = " \" Somebody said something\" said someone"
literal = r'C:\direction\tree'
\n new line
\' '
\\ \
<String>.find(<string>)
finds the target string inside the search string
>> <StartPosition>
-1 := Not Found
<String>.find(<string>, <number 0..>)
finds the iteration of the target string over <number> position
Len(<String>)
Returns the length of the String
<String>[::-1]
Read string backwards
s = 'audacity'
print 'U'+s[-6:]
>> Udacity
22
page #Content of webpage as string
page = '''<div id="top_bin"> <div id="top_content" class="width960"> <div class="udacity float-left"> <a href="/">'''
start_link = page.find("<a href=")
start_url= page.find(β"β,start_link )+1
end_url= page.find(β"β,start_url )
url=page[start_url:end_url]
print url
print("Tick "*20)
raw_literal = r'C/user/documents'
Triple_quotes = ''' Triple quotes
Can extend
Unles \
Is used '''firstname = input(
"Write your first name: "
).title()
surname = input(
"Second name: "
).title()
print(firstname + " " + surname)
word = 'banana'
>>> "nana" in word
True
>>> index = word.find('a')
>>> print(index)
1
>>> word.find('na')
2
>>> word.find('na', 3)
4
>>> line = 'Have a nice day'
>>> line.startswith('Have')
True
>>> line.lower().startswith('h')
True
>>> line.endswith("day")
True
firstname = input(
"Write your first name: "
).title()
surname = input(
"Second name: "
).title()
print(firstname + " " + surname)
π¦Ύ Spaces, tabs, and newlines are normally invisible.
π¦Ύ The built-in function repr can help. It takes any object as an argument and returns a string representation of the object. For strings, it represents whitespace characters with backslash sequences:
>>> s = '1 2\t 3\n 4'
>>> print(s)
1 2 3
4
>>> print(repr(s))
'1 2\t 3\n 4'
|Escape | What it does |
\\ Backslash (\)
\' Single-quote (')
\" Double-quote (")
\a ASCII bell (BEL)
\b ASCII backspace (BS)
\f ASCII formfeed (FF)
\n ASCII linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r Carriage return (CR)
\t Horizontal tab (TAB)
\uxxxx Character with 16-bit hex value xxxx
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx
\v ASCII vertical tab (VT)
\000 Character with octal value 000
\xhh Character with hex value hh