What Is String in Python?
What Is String in Python?
What Is String in Python?
Computers do not deal with characters, they deal with numbers (binary). Even
though you may see characters on your screen, internally it is stored and
manipulated as a combination of 0's and 1's.
script.py
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
print(my_string)
When you run the program, the output will be:
Hello
Hello
Hello
Hello, welcome to
the world of Python
The index of -1 refers to the last item, -2 to the second last item and so on. We can
access a range of items in a string by using the slicing operator (colon).
script.py
str = 'programiz'
#first character
#last character
If we try to access index out of the range or use decimal number, we will get errors.
Slicing can be best visualized by considering the index to be between the elements
as shown below.
If we want to access a range, we need the index that will slice the portion from the
string.
The + operator does this in Python. Simply writing two string literals together also
concatenates them.
The * operator can be used to repeat the string for a given number of times.
script.py
str1 = 'Hello'
str2 ='World!'
# using +
# using *
if(letter == 'l'):
count += 1
print(count,'letters found')
String Membership Test
We can test if a sub string exists within a string or not, using the keyword in.
1. >>> 'a' in 'program'
2. True
3. >>> 'at' not in 'battle'
4. False
Various built-in functions that work with sequence, works with string as well.
# enumerate()
list_enumerate = list(enumerate(str))
#character count
One way to get around this problem is to use triple quotes. Alternatively, we can use
escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use
single quote to represent a string, all the single quotes inside the string must be
escaped. Similar is the case with double quotes. Here is how it can be done to
represent the above text.
script.py
# using triple quotes
Escape
Sequence Description
\\ Backslash
ASCII Bell
\a
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
1. >>> print("C:\\Python32\\Lib")
2. C:\Python32\Lib
3.
4. >>> print("This is printed\nin two lines")
5. This is printed
6. in two lines
7.
8. >>> print("This is \x48\x45\x58 representation")
9. This is HEX representation
print(default_order)
print(positional_order)
print(keyword_order)
count = 0
count += 1
return count
print(string_length('w3resource.com'))
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency('google.com'))
Copy
Sample Output:
{'o': 3, '.': 1, 'g': 2, 'l': 1, 'e': 1, 'c': 1, 'm': 1}
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][1]
Copy
Sample Output:
Exercises
Get a string made of its first three
characters of a specified string
Sample function and result :
first_three('ipy') -> ipy
first_three('python') -> pyt
def first_three(str):
return str[:3] if len(str) > 3 else str
print(first_three('ipy'))
print(first_three('python'))
print(first_three('py'))
print(lexicographi_sort('w3resource'))
print(lexicographi_sort('quickbrown'))
Copy
Sample Output:
['3', 'c', 'e', 'e', 'o', 'r', 'r', 's', 'u', 'w']
['b', 'c', 'i', 'k', 'n', 'o', 'q', 'r', 'u', 'w']
y = -0.25
print()
Copy
Sample Output:
Original Number: 0.25
Formatted Number with percentage: 25.00%
Original Number: -0.25
Formatted Number with percentage: -25.00%
print()
print(str1.count("fox"))
print()
Copy
Sample Output:
1
Reverse a string
def reverse_string(str1):
return ''.join(reversed(str1))
print()
print(reverse_string("abcdef"))
print(reverse_string("Python Exercises."))
print()
Copy
Sample Output:
fedcba
.sesicrexE nohtyP
def reverse_string_words(text):
return(' '.join(line.split()[::-1]))
print(reverse_string_words("Python Exercises."))
Copy
Sample Output:
dog. lazy the over jumps fox brown quick The
Exercises. Python
alphabet = set(string.ascii_lowercase)
input_string = 'The quick brown fox jumps over the lazy dog'
input_string = 'The quick brown fox jumps over the lazy cat'
Copy
Sample Output:
True
False
str1 = "The quick brown fox jumps over the lazy dog."
print(str1.split(' '))
str1 = "The-quick-brown-fox-jumps-over-the-lazy-dog."
print(str1.split('-'))
Copy
Sample Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the',
'lazy', 'dog.']
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the',
'lazy', 'dog.']
vowels = "aeiuoAEIOU"
vowel('w3resource');
Copy
Sample Output:
4
['e', 'o', 'u', 'e']
return str1
print(remove_spaces("a b c"))
Find the maximum occurring character in
a given string
def get_max_occuring_char(str1):
ASCII_SIZE = 256
max = -1
ch = ''
for i in str1:
ctr[ord(i)]+=1;
for i in str1:
max = ctr[ord(i)]
ch = i
return ch
print(get_max_occuring_char("abcdefghijkb"))
Copy
Sample Output:
t
b
return sum_digit
print(sum_digits_string("123abcd45"))
print(sum_digits_string("abcd1234"))
for i in range(len(str)):
else: special_ctr += 1
str = "@W3Resource.Com"
print("Original Substrings:",str)
u, l, n, s = count_chars(str)
Copy
Sample Output:
Original Substrings: @W3Resource.Com
Upper case characters: 3
Lower case characters: 9
Number case: 1
Special case characters: 2