leetcode
  • Coding Interview Prep
  • Data structure
    • String
    • List
    • Matrix
    • Dictionary
    • Tuple
    • Set
    • Tree
    • Stack
  • Array
    • 1_Two Sum
    • 15_Three Sum
    • 21_Merge Two Sorted Lists
    • 26_Remove Duplicates from Sorted Array
    • 27_Remove Element
    • 31_Next Permutation
    • 56_Merge Intervals
    • 57_Insert Interval
    • 66_Plus One
    • 80_Remove Duplicates from Sorted Array II
    • 81_Search in Rotated Sorted Array II
    • 88_Merge Sorted Array
    • 121_Best Time to Buy and Sell Stock
    • 122_Best Time to Buy and Sell Stock II
    • 123_Best Time to Buy and Sell Stock III
    • 167_Two Sum II - Input array is sorted
    • 169_Majority Element
    • 170_Two Sum III - Data Structure Design
    • 189_Rotate Array
    • 238_Product of Array Except Self
    • 243_Shortest Word Distance
    • 244_Shortest Word Distance II
    • 245_Shortest Word Distance III
    • 252_Meeting Rooms
    • 277_Find the Celebrity
    • 283_Move Zeroes
    • 349_Intersection of Two Arrays
    • 350_Intersection of Two Arrays II
    • 605_Can Place Flowers
    • 653_Two Sum IV - Input is a BST
    • 674_Longest Continuous Increasing Subsequence
    • 714_Best Time to Buy and Sell Stock with Transaction Fee
    • 724_Find Pivot Index
    • 747_Largest Number At Least Twice of Others
    • Sort an Array in Wave Form
    • Permute Elements of An Array
    • Reservoir Sampling (online)
    • Reservoir Sampling (offline)
  • Matrix
    • 36_Valid Sudoku
    • 48_Rotate Image
    • 54_Spiral Matrix
    • 59_Spiral Matrix II
    • 118_Pascal's Triangle
    • 119_Pascal's Triangle II
    • 240_Search a 2D Matrix II
    • 311_Sparse Matrix Multiplication
    • 498_Diagonal Traverse
  • String
    • 5_Longest Palindromic Substring
    • 6_ZigZag Conversion
    • 14_Longest Common Prefix
    • 17_Letter Combinations of a Phone number
    • 20_Valid Parentheses
    • 28_Implement strStr()
    • 38_Count and Say
    • 43_Multiply Strings
    • 49_Group Anagrams
    • 93_Restore IP Address
    • 125_Valid Palindrome
    • 151_Reverse Words in a String
    • 157_Read N Characters Given Read4
    • 242_Valid Anagram
    • 266_Palindrome Permutation
    • 344_Reverse String
    • 387_First Unique Character in a String
    • 647_Palindromic Substrings
    • 678_Valid Parenthesis String
    • 680_Valid Palindrome II
    • 709_To Lower Case
    • 819_Most Common Word
    • 833_Find and Replace in String
  • Search
    • 33_Search in Rotated Sorted Array
    • 34_Find First and Last Position of Element in Sorted Array
    • 35_Search Insert Position
    • 153_Find Minimum in Rotated Sorted Array
    • 215_Kth Largest Element in an Array
    • 268_Missing Number
    • 278_First Bad Version
    • 339_Nested List Weight Sum
    • 364_Nested List Weight Sum II
  • Math
    • 12_Integer to Roman
    • 13_Roman to Integer
    • 29_Divide Two Integers
    • 67_Add Binary
    • 69_Sqrt(x)
    • 168_Excel Sheet Column Title
    • 171_Excel Sheet Column Number
    • 204_Count Primes
    • 504_Base 7
    • 628_Maximum Product of Three Numbers
    • Multiply Two Integers
    • Smallest Non-constructible Value
    • SORT5
  • DP
    • 53_Maximum Subarray
    • 152_Maximum Product Subarray
    • 256_Paint House
    • 300_ Longest Increasing Subsequence
    • 747_Min Cost Climbing Stairs
    • 377_Combination Sum IV
  • Hash Table
    • 535_Encode and Decode TinyURL
  • Tree
    • 94_Binary Tree Inorder Traversal
    • 102_Binary Tree Level Order Traversal
    • 103_Binary Tree Zigzag Level Order Traversal
    • 104_Maximum Depth of Binary Tree
    • 113_Path Sum II
    • 144_Binary Tree Preorder Traversal
    • 145_Binary Tree Postorder Traversal
    • 235_Lowest Common Ancestor of a Binary Search Tree
    • 236_Lowest Common Ancestor of a Binary Tree
    • 257_Binary Tree Paths
    • 404_Sum of Left Leaves
    • 543_Diameter of Binary Tree
    • 572_Subtree of Another Tree
    • 637_Average of Levels in Binary Tree
  • Linked List
    • 2_Add Two Numbers
    • 206_Reverse Linked List
    • 234_Palindrome Linked List
  • Recursion
    • Tower of Hanoi
  • Backtracking
    • 51_N-Queens
    • 52_N-Queens II
    • 46_ Permutations
    • 77_ Combinations
    • 78_Subsets
    • 22_Generate Parentheses
    • 131_ Palindrome Partitioning
  • Bit Manipulation
    • 461_Hamming Distance
  • Python
    • for ... else ...
    • dictionary.get( ) vs dictionary[ ]
    • Read and write data file
    • List Comprehension
    • Lambda
    • Receiving Tuples and Dictionaries as Function Parameters
    • The assert statement
    • Miscellaneous
    • Python shortcuts
  • template
  • facebook
Powered by GitBook
On this page

Was this helpful?

  1. Data structure

String

Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and doc strings.

string = "Hello world!"
print string
# Hello world!

mystring = '''first line 
second line
third line'''
print mystring
# first line 
# second line
# third line

print('''He said, "What's there?"''')
# He said, "What's there?"            # using triple quotes

print('He said, "What\'s there?"')
# He said, "What's there?"            # escaping single quotes

print("He said, \"What's there?\"")
# He said, "What's there?"            # escaping double quotes

Convert from other type with str()

#convert from integer to string
str(1)

Slicing: similar as in list

string = "Hello world!"
print string[3]
# l                   # return the 4th character
print string[3:7]
# lo w                # return the 4th to 7th character
print string[:7]
# Hello w             # from the beginning to the 7th character
print string[3:]
# lo world!           # from the 4th to the end
print string[-3:]
# ld!                 # 3rd character from the end until the end
print string[3:8:2]
# l o                 # [start:stop:step]

Reverse

Note that reverse() doesn't work for string. Need to convert string to list and then reverse().

print string[::-1]
# !dlrow olleH

Important: We can't do slicing and reverse simultaneously. If we want to reverse a substring:

string[start:end][::-1]

Change a string

Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. We can simply reassign different strings to the same name.

string = "Hello world!"
string[0] = "h"
print string
# TypeError: 'str' object does not support item assignment

string = "hello world!"
print string
# hello world!

Delete characters from a string

We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword

del.

string = "hello world!"
print string
# hello world!
del string
print string
# NameError: name 'string' is not defined

Concatenation of Two or More Strings

Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also concatenates them.

The * operator can be used to repeat the string for a given number of times.

string1 = "hello"
string2 = "world"

print string1 + string2
# helloworld

whole = string1 + " " + string2
print whole
# hello world

print string1 * 2 + " " + string2
# hellohello world

String Membership Test

We can test if a sub string exists within a string or not, using the keywordin.

print "l" in "hello"
# True

print "l" not in "hello"
# False

String Comparison

We can use == to compare if two strings are the same.

"abc" == "ab"
# False
"abc" == "abc"
# True

Iterate each character in a string

word = 'test'
for c in word:
    print c

for i, c in enumerate(word):
    print i, c

Convert all characters to uppercase/lowercase

These make a new string with all letters converted to uppercase and lowercase, respectively.

print string.upper()
# HELLO WORLD!
print string.lower()
# hello world!

startswith/endswith

This is used to determine whether the string starts with something or ends with something, respectively.

print string.startswith("Hello")
# True
print string.startswith("hello")
# False
print string.endswith("!")
# True

Split

This splits the string into a bunch of strings grouped together in a list. If not specified, the default of string.split() is splitting by space.

print string.split(" ")
# ['Hello', 'world!']
print string.split("l")
# ['He', '', 'o wor', 'd!']

Enumerate

The enumerate()function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.

string = 'cold'
print list(enumerate(string))
# [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]

Join strings

print ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
# This will join all words into a string

print '#'.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
# This#will#join#all#words#into#a#string

Length

Length including punctuation and spaces.

len(string)
# 12

Count

differentiate uppercase and lowercase

can count the number of space

can count the number of punctuation

print string.count("l")
# 3
print string.count("h")
# 1
print string.count("H")
# 0 
print string.count(" ")
# 1
print string.count("!")
# 1

Finding substring

Both index and find return the index of the first occurrence of the first character in the substring. The only difference is that when the substring is not found, index returns ValueError and find returns -1.

string = "hello world"

print string.index("l")
# 2
print string.index("ll")
# 2

print string.find("l")
# 2
print string.find("ll")
# 2

print string.index("lll")
# ValueError: substring not found

print string.find("lll")
# -1

Replace part of a string

When using replace() to replace part of a string, need to assign the new value to the original name. Because string is immutable. Otherwise, the string won't be changed.

string = "hello world"
string = string.replace("hello", "Hello")
print string
# Hello world

Check if a string is letter

str.isalpha()Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

string = 'abc'
print string.isalpha()
# True

A list of build-in functions for strings

Method

Description

Converts first character to Capital Letter

Pads string with specified character

converts to casefolded strings

returns occurrences of substring in string

Checks if String Ends with the Specified Suffix

Replaces Tab character With Spaces

returns encoded string of given string

Returns the Highest Index of Substring

formats string into nicer output

Returns Index of Substring

Checks Alphanumeric Character

Checks if All Characters are Alphabets

Checks Decimal Characters

Checks Digit Characters

Checks for Valid Identifier

Checks if all Alphabets in a String are Lowercase

Checks Numeric Characters

Checks Printable Character

Checks Whitespace Characters

Checks for Titlecased String

returns if all characters are uppercase characters

Returns a Concatenated String

returns left-justified string of given width

returns right-justified string of given width

returns lowercased string

returns uppercased string

swap uppercase characters to lowercase; vice versa

Removes Leading Characters

Removes Trailing Characters

Removes Both Leading and Trailing Characters

Returns a Tuple

returns a translation table

Returns a Tuple

returns mapped charactered string

Replaces Substring Inside

Returns the Highest Index of Substring

Returns Highest Index of Substring

Splits String from Left

Splits String From Right

Splits String at Line Boundaries

Checks if String Starts with the Specified String

Returns a Title Cased String

Returns a Copy of The String Padded With Zeros

Formats the String Using Dictionary

Checks if any Element of an Iterable is True

returns true when all elements in iterable is true

Returns String Containing Printable Representation

Coverts a Value to Boolean

returns array of given byte size

returns immutable bytes object

Returns a Python code object

Creates a Complex Number

Returns an Enumerate Object

constructs iterator from elements which are true

returns floating point number from number, string

reads and returns a line of string

returns integer from a number or string

returns iterator for an object

Returns Length of an Object

returns largest element

returns smallest element

Applies Function and Returns a List

returns Unicode code point for Unicode character

returns reversed iterator of a sequence

creates a slice object specified by range()

returns sorted list from a given iterable

Add items of an Iterable

Returns an Iterator of Tuples

PreviousData structureNextList

Last updated 3 years ago

Was this helpful?

Python String capitalize()
Python String center()
Python String casefold()
Python String count()
Python String endswith()
Python String expandtabs()
Python String encode()
Python String find()
Python String format()
Python String index()
Python String isalnum()
Python String isalpha()
Python String isdecimal()
Python String isdigit()
Python String isidentifier()
Python String islower()
Python String isnumeric()
Python String isprintable()
Python String isspace()
Python String istitle()
Python String isupper()
Python String join()
Python String ljust()
Python String rjust()
Python String lower()
Python String upper()
Python String swapcase()
Python String lstrip()
Python String rstrip()
Python String strip()
Python String partition()
Python String maketrans()
Python String rpartition()
Python String translate()
Python String replace()
Python String rfind()
Python String rindex()
Python String split()
Python String rsplit()
Python String splitlines()
Python String startswith()
Python String title()
Python String zfill()
Python String format_map()
Python any()
Python all()
Python ascii()
Python bool()
Python bytearray()
Python bytes()
Python compile()
Python complex()
Python enumerate()
Python filter()
Python float()
Python input()
Python int()
Python iter()
Python len()
Python max()
Python min()
Python map()
Python ord()
Python reversed()
Python slice()
Python sorted()
Python sum()
Python zip()