Python String

0 0
Read Time:1 Minute, 6 Second

Python String

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

For example:

str = 'Hello World!'

print(str)          # Prints complete string
print(str[0])       # Prints first character of the string
print(str[2:5])     # Prints characters starting from 3rd to 5th
print(str[2:])      # Prints string starting from 3rd character
print(str * 2)      # Prints string two times
print(str + "TEST") # Prints concatenated string

Output:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Multiline Strings

You can assign a multiline string to a variable by using three double quotes (“”” “””)or single quotes (”’ ”’):

str = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(str)

Traversing Through a String

Since strings are arrays, we can traverse through the characters in a string, with a for loop.

Example:

for x in "CodeDixa":
  print(x)
/*
Output:
C
o
d
e
D
i
x
a

*/
Happy
Happy
100 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment