Skip to content

Latest commit

 

History

History
275 lines (185 loc) · 5.75 KB

File metadata and controls

275 lines (185 loc) · 5.75 KB

String

Strings in Python are: Texts wrapped in single, double or triple quotes. Or, we can say, a string is a sequence of characters. We can use single quotes or double quotes to represent a string.

For example:

str1 = "Hello"

str2 = 'John Snow'

str3 = "12345" 

str4 = '_$%""^&*()!-='

str5 = """this is also a string
expanded in 
multiple line
"""

Methods for concatenating strings

fname = "John"
lname = "Doe"

# Method 1:
print(fname, lname)

# Method 2:
print(fname + ' ' + lname)

# Method 3:
print("Name: {0} {1}".format(fname, lname))

# Method 4:
print(f"Name: {fname} {lname}")

With Python > 3.8 we can do

name = 'John Doe'
age = 30

# We can put the variables names inside curly brackets.
print(f"{name=}, {age=}")
# Output: name='John Doe', age=30

print(f'{name=} {age=}')
# Output: name='John Doe', age=30
# This is called: Self-documenting expression with the '=' character.

Escape Sequence

Printing double quote "" or single quotes '' inside a string.

# How do we print:
# s = "He said, "I am learning Python Programming language." "

# Method-1: Using combination of single and double quotes.
s = 'He said, "I am learning Python Programming language." '
print(s)  # Output: He said, "I am learning Python Programming language."

# Method-2: Using escape character '\'.
s = "He said, \"I am learning Python Programming language.\" "
print(s)  # Output: He said, "I am learning Python Programming language."

Escaping a 'escape character'?

# Using two escape characters.

s = "I am learning \\Python Programming\\ language"
print(s)  # Output: I am learning \Python Programming\ language

Adding & Multiplying strings

s = "Python"
print(s + s)
# Output: PythonPython

s = "Python" * 5
print(s)

# Output:
PythonPythonPythonPythonPython

String Indexing and Slicing

String indexing is a way to access individual characters in a string. Indexing starts at 0, so the first character in a string is at index 0, the second character is at index 1, and so on.

For example:

# String indexing is to get the element at the required index.

s = "I am learning Python Programming language"

print(s[0])         # Output: I (first character)

print(s[2])         # Output: a (character at position 2)

print(s[-2])        # Output: g (second last character)

String slicing is a way to get a sub-string from a string by specifying a range of indices.

# Syntax for string slicing: [start:stop:step]

s = "I am learning Python Programming language"

print(s[0:10])      # Output: I am learn

print(s[10:25])     # Output: ing Python Prog

print(s[::2])       # Output: Ia erigPto rgamn agae

# Reverse the string
print(s[::-1])      # Output: egaugnal gnimmargorP nohtyP gninrael ma I

Length of string

# in-built len() function to calculate the length of the string
s = "I am learning Python Programming language"
print(len(s))

# Output:
41

Using in operators in string

word = "Python"

print("t" in word)      # True
print("k" in word)      # False
print("o" in word)      # True

Strings: Useful methods

s = "I am learning Python Programming language"

print(s.capitalize())       
# Output: I am learning python programming language

print(s.count('o'))
# Output: 2

print(s.endswith('e'))
# Output: True

print(s.find('z'))
# Output: -1

print(s.isdigit())
# Output: False

print(s.islower())
# Output: False

print(s.isnumeric())
# Output: False

print(s.isprintable())
# Output: True

print(s.lower())
# Output: i am learning python programming language

print(s.replace('a', 'o'))
# Output: I om leorning Python Progromming longuoge

print(s.split())
# Output: ['I', 'am', 'learning', 'Python', 'Programming', 'language']

print(s.startswith('k'))
# Output: False

print(s.title())
# Output: I Am Learning Python Programming Language

print(s.upper())
# Output: I AM LEARNING PYTHON PROGRAMMING LANGUAGE

Strings: Output formats

# To get the output of 3 print statements in a single line use end=' '

lang1 = "Python"
lang2 = "Java"
lang3 = "Ruby"

print(lang1, end=' ')
print(lang2, end=' ')
print(lang3)

# Output:
Python Java Ruby

New line

# Use '\n' to print a new line

s = "I am learning\n Python Programming language"
print(s)

# Output: 
I am learning
 Python Programming language

Tab

# Use '\t' to print a tab

s = "I am learning\t Python Programming language"
print(s)

# Output
I am learning    Python Programming language

Windows path

# Here \n will print a new line

filepath = "C:\dirpath\name_of_file"
print(filepath)

# Output:
C: \dirpath
ame_of_file

Instead use r (raw string)

# Using raw string by adding 'r' in front of the string

filepath = r"C:\dirpath\name_of_file"
print(filepath)

# Output:
C:\dirpath\name_of_file

String: Get complete list of methods

s = "Learning PYTHON"
print([item for item in dir(s) if not item.startswith('_')])

# Output:
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']