3.3. Strings - JulTob/Python GitHub Wiki

πŸ› Character

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

"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]."

🐊 String Object

text = 'wasssap'
print(text)

πŸ¦• Casting

πŸ¦• Casting transforms a diferent type into a string of text.

str() #Cast

🐒 Format String

🐒 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}")

🦚 Clear format

# Remove Whitespace
text = "   Avada    Kedabra   \n".strip()
# "Avada Kedabra"

πŸ‰ Capitalization

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

🦎 String properties

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

🐝 Repetition

multiplication= "Na β€œ * 3  #  Na Na Na  # Repeat

🐜🐜 Concatenation

Text = β€œsome” + β€œ β€œ + β€œwords” + β€œ β€œ + β€œconcatenate”
Text = β€œsome” β€œ β€œ β€œliterals” β€œ β€œ β€œconcatenate” β€œautomatically” β€œ.”

🦈 Slicing

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)

πŸ¦‘ Special strings

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)

🐿 Finding

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

πŸ•Š String Input

firstname = input(
    "Write your first name: "
    ).title()
surname =  input(
    "Second name: "
    ).title()


print(firstname + " " + surname)

🦾 Representation

🦾 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 Characters

|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
⚠️ **GitHub.com Fallback** ⚠️