5. String – working with strings

1.String Concatenation: Join string together is called string concatenation.

a="hello"+" "+"world"
print(a)
#output
Hello world

2.String Repetition: * operator is used for repeating strings any number of times as required.

a = "$" * 10
print(a) 
#output
$$$$$$$$$$

3.Length of String: len() returns the number of characters in a given string.

username = input() # Ravi
length = len(username)
print(length)
4

4.String Indexing: We can access an individual character in a string using their
positions (which start from 0) . These positions are also called index.

username = "Ravi"
first_letter = username[0]
print(first_letter)
P

5.String Slicing: Obtaining a part of a string is called string slicing. Start from the
start_index and stops at the end_index. (end_index is not included in the slice).

message = "Hi Ravi"
part = message[3:7]
print(part) 
Rvai

6.Slicing to End: If end_index is not specified, slicing stops at the end of the string.

message = "Hi Ravi"
part = message[3:]
print(part)
Ravi

7.Slicing from Start: If the start_index is not specified, the slicing starts from the index 0.

message = "Hi Ravi"
part = message[:2]
print(part) 
Hi

8.Negative Indexing: Use negative indexes to start the slice from the end of the string.

b = "Hello, World!"
print(b[-5:-2]) 
orl

9.Reversing String: Reverse the given string using the extended slice operator.

txt = "Hello World"
txt = txt[::-1]
print(txt) 
dlroW olleH

10.Membership check-in strings:
in: By using the in operator, one can determine if a value is present in a sequence or
not.

language = "Python"
result = "P" in language
print(result)
True

11.not in: By using the, not in operator, one can determine if a value is not present in a sequence or not.

language = "Python"
result = "P" not in language
print(result) 
False

Leave a comment

Blog at WordPress.com.

Design a site like this with WordPress.com
Get started