Python string- The data type of Words and Character

Image credit:Real Python

Strings

Strings are data type of alphabets and characters.

Double quotes ” ” and ‘ ‘ quotes are the same in python.

Assigning string to a variable

The string can be assigned to a variable with the “=” sign.

a="all"
b="call"

Multiline strings

Multiline strings are denoted by “”” “””.

A multiline string is used for displaying string more than one line.

Multiline strings

Strings are arrays

Strings in python are arrays of bytes representing Unicode character.

Python does not have a character type. They represented as length of 1.

Square brackets can be used to access an elements of the string.

String as arrays

Looping through a string

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

Loop

String length

To get the length of a string use the len() function.

Length of the string

Check string

To check if a certain keyword is present in the string, we can use the keyword in.

in keyword

Use in in if statement

in used in if statement

Check if Not

To check if a certain character is not present in a string.

You can use keyword not in.

Use it in an if statement

Python string Operation

Concatenation

1. With the help of the + sign we can combine two strings.

a="hello "
b="world!"
print(a+b)

hello world!

Multiplication

1. With the help of multiplication the string increasing the number of times.

a="hello "
print(a*3)

hello hello hello

2. We used the * sign.

String formatting escape sequence

The string character inside the string can’t be print.

If I have to print string character inside the string. We can use an escape character or a triple quote.

For example, if you have to print Hey, “what are you doing?”. We can print this with an escape character.

print("Hey,\'what are you doing?'")

Hey,'what are you doing?'

Conclusion

Python string is a data type of words and alphabets. There are many operations that you can perform on python string. They are concatenation, multiplication and escape sequences.

https://vipulkunwar503.code.blog/2021/06/13/python-syntax/

https://vipulkunwar503.code.blog/2021/06/14/python-variables/

Leave a comment