-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings_practice.py
More file actions
100 lines (78 loc) · 1.81 KB
/
strings_practice.py
File metadata and controls
100 lines (78 loc) · 1.81 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#Print the second letter of the string:
a = "Hello, World!"
print(a[1])
#loop through the letters in the word "banana":
for x in "banana":
print(x)
#length of a string
print(len(a))
#check if "free" is present in the string:
txt = "The best things in life are free!"
print("free" in txt)
if "free" in txt:
print("Yes, 'free' is present.")
#
b = " Hello, World! "
# slice the charcters from exact position
print(b[2:5])
# slice from the start
print(b[:5])
# slice to the end
print(b[2:])
# slice with negative index
print(b[-5:-2])
# modify the string
print(b.upper())
print(b.lower())
print(b.strip())
print(b.replace("H", "J"))
print(b.split(","))
# concatenate strings
a = "Hello"
b = "World"
c = a + " " + b
print(c)
# format strings fstrings
age = 36
txt = f"My name is John, I am {age}"
print(txt)
# placeholders and modifiers
price = 59
txt = f"The price is {price} dollars"
print(txt)
txt = f"The price is {price:.2f} dollars"
print(txt)
txt = f"The price is {20 * 59} dollars"
print(txt)
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
#Escape Character
#To insert characters that are illegal in a string, use an escape character.
#An escape character is a backslash \ followed by the character you want to insert.
# Single Quote
txt = 'It\'s alright.'
print(txt)
# backslash
txt = "This will insert one \\ (backslash)."
print(txt)
# new line
txt = "Hello\nWorld!"
print(txt)
#carriage return
txt = "Hello\rWorld!"
print(txt)
# tab
txt = "Hello\tWorld!"
print(txt)
#backspace
txt = "Hello\bWorld!"
print(txt)
# Form feed
txt = "Hello\fWorld!"
print(txt)
# octal value
txt = "Hello\110\145\154\154\157"
print(txt)
# hexadecimal value
txt = "Hello\x48\x65\x6c\x6c\x6f"
print(txt)