Tuesday, 4 September 2018

Strings


Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
String literals in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
Strings can be output to screen using the print function. For example: print("hello").
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Example

Ex1:-Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
output:-
e
Ex2:-
Substring. Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
output:- llo
Ex3:-
The len() method returns the length of a string:
a = "Hello, World!"
print(len(a))
output:- 13

Ex4:-
 a = "Hello, World!"
print(a.replace("H", "J"))
output:- Jello, World!

Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −
#!/usr/bin/python3
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
When the above code is executed, it produces the following result −
var1[0]:  H
var2[1:5]:  ytho

No comments:

Post a Comment

Lists

Python  Lists Python Collections (Arrays) There are four collection data types in the Python programming language: List  is a ...