mykhailohoy
mykhailohoy

Reputation: 482

Is there any difference between string and array of one-digit strings in Python?

Quoting w3schools,

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

Is there any difference between 'abc' and ['a', 'b', 'c']? Is there a way to tell the difference between the first and the second example without using type()?

Upvotes: 1

Views: 1125

Answers (2)

Barmar
Barmar

Reputation: 781059

Note that what you quoted says "array of bytes". ['a', 'b', 'c'] is a list, not an array. They're talking about the internal representation as an array in memory, not how it's used in the language.

Many operations work differently on strings and lists. In particular, searching operations look for substrings in strings, but just single elements in lists.

s = 'abc'
l = ['a', 'b', 'c']
print('ab' in s) # prints True
print('ab' in l) # prints False

There are also many operations that only work with one or the other type. For example, regular expression matching will work on strings, not lists. Strings are immutable, so modification operations like append() and pop() only work with lists.

Upvotes: 2

jsbueno
jsbueno

Reputation: 110301

Strings in Python are not "arrays of Bytes". They are first class objects - yes, the underlying object do have a buffer where the bytes representing the unicode characters are stored - but that is opaque.

Now, strings are sequences of one-character strings (not bytes, not other type). As thus, most code that also accepts or expects sequences of one-character strings will work with a string of any-size, as well as any other such sequence, such as a list of one-character strings as in your example.

Other than that, strings are fundamentally different from "lists of strings". Probably the most used way to visualize strings is a simple "print", and a print of a string and such a list will differ enormously.

Then, if you need to find the diference in code, using type, or calling isinstance(myvar, str) should be enough.

Upvotes: 2

Related Questions