-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasic-string-operations.py
More file actions
110 lines (61 loc) · 2.06 KB
/
basic-string-operations.py
File metadata and controls
110 lines (61 loc) · 2.06 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
101
102
103
104
105
106
107
108
109
110
# find len of string
astring = "Hello world!"
print("single quotes are ' '")
print(len(astring))
# find the index of a character in a string
astring = "Hello world!"
print(astring.index("o"))
# print how many a character appear in a string
astring = "Hello world!"
print(astring.count("l"))
# print only some character in a string (string slicing)
astring = "Hello world!"
print(astring[3:7])
# [start:stop:step]
astring = "Hello world!"
print(astring[3:7:2])
# reverse a string
astring = "Hello world!"
print(astring[::-1])
# string upper and lower
astring = "Hello world!"
print(astring.upper())
print(astring.lower())
# determine is a string is started or ends with something
astring = "Hello world!"
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))
# splitting the string
astring = "Hello world!"
afewwords = astring.split(" ")
print(afewwords)
'''
EXERCISE
fix the code bellow
'''
s = "Hey there! what should this string be?"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))