-
Notifications
You must be signed in to change notification settings - Fork 0
/
1. String.py
74 lines (55 loc) · 1.3 KB
/
1. String.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# strings are immutable in python
name = "Asad"
# format string to user variables
s = f"HELLO {name}"
s.upper()
s.lower()
s.swapcase()
# capitalize first letter
s.capitalize()
# capitalize every word
s = s.title()
# -------------------
# remove whitespace
s.strip()
# from individual sides
s.lstrip()
s.rstrip()
# -------------------
# Replace String
s.replace("H", "J")
# return comma separated list
s.split(',')
# Slicing
s[2:5]
# from start
s[:5]
# to end
s[2:]
# Negative Indexing
s[-5:-2]
# return index of searched letter
print(s.index("R"))
# ------------------
# Format String
txt = "My name is John, and I am {}"
print(txt.format(36))
# Formatting Types
# https://www.w3schools.com/python/ref_string_format.asp
txt = "My name is John, and I am {:.2f}"
# Index Numbers
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(25, 30, 35))
# Named Indexes
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
# multiline string
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
# Check String
# if a certain phrase or character is present in a string with 'in'
txt = "The best things in life are free!"
if "free" in txt:
print("ok")