-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path02_strings.py
More file actions
60 lines (45 loc) · 1.29 KB
/
02_strings.py
File metadata and controls
60 lines (45 loc) · 1.29 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
sample_str = "This-is-a-sample-string"
print(sample_str)
# How to access individual characters from a string
print(sample_str[8])
# Slicing
sub_str = sample_str[2:7]
print(sub_str)
sub_str = sample_str[:]
print(sub_str)
sub_str = sample_str[1:]
print(sub_str)
sub_str = sample_str[:5]
print(sub_str)
sub_str = sample_str[::2]
print(sub_str)
# Reverse a string
sub_str = sample_str[::-1]
print("Reversed string:", sub_str)
# Length of a string
len_str = len(sample_str)
print("Length of a string:", len_str)
# Method
sample_str = "hello"
print(sample_str.capitalize()) # "Hello"
# split(), join(), format(), count(), strip(), lstrip(), rstrip()
sample_str = "This is a sample string"
str_split = sample_str.split() # output: list
print(str_split, type(str_split))
join_split_str = " ".join(str_split)
print(join_split_str, type(join_split_str))
count_a = sample_str.count('a')
print(count_a)
sample_str = " devops is a very good career choice "
strip_str = sample_str.strip()
print(strip_str)
# Strings are immutable
sample_str = "This is a sample string"
sample_str[-1] = 'G'
print(sample_str)
"""
Traceback (most recent call last):
File "/home/cloudshell-user/python-devops/02_strings.py", line 52, in <module>
sample_str[-1] = 'G'
TypeError: 'str' object does not support item assignment
"""