DEV Community

Cover image for Learn Python: strings
Rishi
Rishi

Posted on • Edited on

Learn Python: strings

strings

A string can be declared using either single' or double" quotations.

### A string with double quotation my_string1 = "Hello, Rishi" ### A string with single quotation my_string2 = 'Hello, Rishi' print(my_string1) print(my_string2) 
Enter fullscreen mode Exit fullscreen mode

Using single' and double" quotations

Both single' and double" quotations can be used while declaring a string.

### A string with mixed quotations string_mixed = "Hello, Rishi: 'You are amazing'!" print(string_mixed) string_mixed2 = 'Hello, Rishi: "You are amazing"!' print(string_mixed2) 
Enter fullscreen mode Exit fullscreen mode

Escaping single' and double" quotations

To use the same quotations within the string declaration, an escape character \ needs to be used.

 ### A string with mixed quotations using an escape character string_mixed3 = "Hello, Rishi: \"You are amazing\"!" print(string_mixed3) string_mixed4 = 'Hello, Rishi: \'You are amazing\'!' print(string_mixed4) 
Enter fullscreen mode Exit fullscreen mode

Multi-line strings - Double Quotes

Multi lines string starts and ends with triple double-quotations """.
This triple double-quotations """ can be used for long comments within a python code.

### Multi-line strings - Double Quotes  multiple_lines = """Hello, My name is Rishi. Welcome. """ print(multiple_lines) """Hello, This is a very long comments. """ 
Enter fullscreen mode Exit fullscreen mode

Multi-line strings - Single Quotes

Multi lines string starts and ends with triple double-quotations '''.
This triple double-quotations ''' can be used for long comments within a python code.

### Multi-line strings - Single Quotes  multiple_lines = '''Hello, My name is Rishi. Welcome. ''' print(multiple_lines) '''Hello, This is a very long comments. ''' 
Enter fullscreen mode Exit fullscreen mode

Adding a string to another string

### Adding a string to another string  greet = "Hello" name = "Rishi" print(greet + name); print(greet + ' ' + name); 
Enter fullscreen mode Exit fullscreen mode

Adding a string to a number!!! Wait? 😕

Before adding a string to a number, we need to convert it first using str().

### Adding a string to a number!!! Wait? greet = "Hello" number_as_string = str(2020) float_as_string = str(0.12345) print(greet + number_as_string); print(greet + ' ' + number_as_string); print(greet + ' ' + float_as_string) 
Enter fullscreen mode Exit fullscreen mode



Top comments (0)