Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - String

Back


Strings

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""

print(a)

a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Strings are Arrays

a = "Hello, World!"
print(a[0]) #H
print(a[1]) #e
print(a[len(a)-1]) #!

for x in a:
    print(x)

# H
# e
# !
# H
# e
# l
# l
# o
# ,

# W
# o
# r
# l
# d
# !

String: More than one line

xStr = ''' Hello,
    world'''

print(xStr)
#  Hello,
#     world

String Length: len()

a = "Hello, World!"
print(len(a))   #13

String Check: in

txt = "The best things in life are free!"

print("free" in txt)    # true
print("expensive" not in txt)   # true

if "free" in txt:
  print("Yes, 'free' is present.")

if "expensive" not in txt:
  print("No, 'expensive' is NOT present.")

String Slicing

b = "Hello, World!"

print(b[0]) # H
print(b[0:1]) # H not inclusive
print(b[2:5]) # llo
print(b[:5]) # Hello
print(b[2:]) # llo, World!
print(b[-5:-2]) # orl

arr = "ABCDEFG"

print(arr[::])  # ABCDEFG, grap all characters
print(arr[::1])  # ABCDEFG, grap all characters
print(arr[::2])  # ACEG, grap characters from beginning to the end with step of 2
print(arr[::-1])  # GFEDCBA, with step of -1 means reverse all order
print(arr[::-2])  # GECA, reverse with step of 2

String Function

# String function

print("\n--------Upper Case--------\n")
a = "Hello, World!"
print(a.upper())    # HELLO, WORLD!


print("\n--------Lower Case--------\n")
a = "Hello, World!"
print(a.lower())    # hello, world!


print("\n--------Remove Whitespace--------\n")
a = "    Hello, World!    "
print(a.strip())    # "Hello, World!"


print("\n--------Replace String--------\n")
a = "Hello, World!"
print(a.replace("H", "J"))  # Jello, World!


print("\n--------Split String--------\n")
a = "Hello, World!"
print(a.split(",")) # ['Hello', ' World!']


String Concatenation

# String Concatenation

print("\n--------+--------\n")
a = "Hello"
b = "World"
c = a + b
print(c)    # HelloWorld

age = 36
txt = "My name is John, I am"
print(txt,age)  # My name is John, I am 36

String Format

str.format() Method

# String Format

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))  # My name is John, and I am 36


quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))  # I want 3 pieces of item 567 for 49.95 dollars.


quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))  # I want to pay 49.95 dollars for 3 pieces of item 567.

myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
# I have a Ford, it is a Mustang.

F-string Method


print("\n--------f-string--------\n")

print("\n--------variable--------")
val = 'Geeks'
# GeeksforGeeks is a portal for Geeks.
print(f"{val}for{val} is a portal for {val}.")
name = 'Tushar'
age = 23
# Hello, My name is Tushar and I'm 23 years old.
print(f"Hello, My name is {name} and I'm {age} years old.")


print("\n--------expressions--------")
print(f"{2 * 30}")  # 60


print("\n--------fuction--------")


def upercase(input):
    return input.upper()


name = "Sachin Tendulkar"
print(f"{upercase(name)} is great.")    # SACHIN TENDULKAR is great.


print("\n--------fuction--------")


class Actor:
    def __init__(self, first_name, last_name, movie):
        self.first_name = first_name
        self.last_name = last_name
        self.movie = movie

    def __str__(self):
        return f"{self.first_name} {self.last_name}'s superhit movie is {self.movie}."

    def __repr__(self):
        return f"{self.first_name} {self.last_name}  {self.movie}. Superhi!"


ac = Actor('Keenu', 'Reevs', 'Matrix')
print(f"{ac}")  # Keenu Reevs's superhit movie is Matrix.


print("\n--------Dictionary--------")

detail = {"name": "John", "age": 19}
# John is 19 years old.
print(f"{detail['name']} is {detail['age']} years old.")


print("\n--------Braces--------")

print(f"{70 + 40}")         # 110
print(f"70")       # {70 + 40}
print(f"}")     # {110}
print(f"}}")    # 70

Escape Character

An escape character is a backslash \ followed by the character you want to insert.

Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
txt = "We are the so-called \"Vikings\" from the north."
print(txt)  # We are the so-called "Vikings" from the north.

Prefix: b"", r""


String Methods

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
format_map() Formats specified values in a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

TOP